RDF文件的解析

开发过程中的XML解析有很多种方式

一次偶然的机会,碰到RDF格式的,和传统的xml有点区别,可能有他自己的独特之处

 

普通的xml解析可能无效 ,在网上搜索了下 ,建议用jena解析

可以在主页下载:http://jena.sourceforge.net/  当前版本为 jena-2.6.4

 

先看下RDF的大致格式



	
		
			
				
				PhoneKeypad
				1
				84x30
				10x3
				
					Yes
				
				Nokia
				3330
				Yes
			
		

	

 

 

 

解析部分代码

 

/**
     * 
     * 解析RDF 文件
     * 
     * @param inputFile
     * @author
     * @date 2011-9-1 上午09:17:16
     */
    private void parseRdfFile(File inputFile)
    {
        try
        {

            Model model = ModelFactory.createDefaultModel();
            // use the FileManager to find the input file
            InputStream in = new FileInputStream(inputFile);
            if (in == null)
            {
                throw new IllegalArgumentException("File:  not found");
            }
            model.read(new InputStreamReader(in), "");
            StmtIterator stmtIt = model.listStatements();

            String key1 = "";
            String key2 = "";
            String value = "";

            while (stmtIt.hasNext())
            {

                Statement stmt = stmtIt.nextStatement();
                // resource
                key1 = stmt.getSubject().getURI();

                if (null == key1)
                {
                    continue;
                }

                // Property
                key2 = stmt.getPredicate().getLocalName();

                // RDFNode
                if (stmt.getBag().size() > 0)
                {
                    value = getBagStr(stmt.getBag());
                } else
                {
                    value = stmt.getObject().toString();
                }

                // key1
                logger.trace("resource:" + key1);

                // key2
                logger.trace("Property = " + key2);

                // value
                logger.trace("RDFNode/bag = " + value);

               
            }

        } catch (Exception e)
        {
            logger.error("parseRdfFile Failed", e);
        }
    }

    /**
     * 
     * 获取bag 的值
     * 
     * @param bags
     * @return
     * @author
     * @date 2011-9-1 上午07:26:51
     */
    private String getBagStr(Bag bags)
    {
        if (null == bags || bags.size() == 0)
        {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        NodeIterator bagIt = bags.iterator();
        if (bagIt.hasNext())
        {
            while (bagIt.hasNext())
            {
                sb.append(bagIt.next());
                sb.append(MARK_SEP);
            }
        }

        return sb.substring(0, sb.length() - 1 - MARK_SEP.length());
    }

 

你可能感兴趣的:(XML相关)