开发过程中的XML解析有很多种方式
一次偶然的机会,碰到RDF格式的,和传统的xml有点区别,可能有他自己的独特之处
普通的xml解析可能无效 ,在网上搜索了下 ,建议用jena解析
可以在主页下载:http://jena.sourceforge.net/ 当前版本为 jena-2.6.4
先看下RDF的大致格式
<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:prf="http://www.wapforum.org/profiles/UAPROF/ccppschema-20010430#">
<rdf:Description rdf:about="Nokia3330">
<prf:component>
<rdf:Description rdf:about="HardwarePlatform">
<rdf:type
rdf:resource="http://www.wapforum.org/profiles/UAPROF/ccppschema-20010430#HardwarePlatform" />
<prf:Keyboard>PhoneKeypad</prf:Keyboard>
<prf:NumberOfSoftKeys>1</prf:NumberOfSoftKeys>
<prf:ScreenSize>84x30</prf:ScreenSize>
<prf:ScreenSizeChar>10x3</prf:ScreenSizeChar>
<prf:StandardFontProportional>
Yes
</prf:StandardFontProportional>
<prf:Vendor>Nokia</prf:Vendor>
<prf:Model>3330</prf:Model>
<prf:TextInputCapable>Yes</prf:TextInputCapable>
</rdf:Description>
</prf:component>
</rdf:Description>
</rdf:RDF>
解析部分代码
/**
*
* 解析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());
}
|