假设我们有以下 xml
<books>
<book>
<id>...</id>
<title>...</title>
<references>
<book>
<id>...</id>
<title>...</title>
</book>
</references>
<authors>
<author>
<id>...</id>
<name>...</name>
<written-books>
<book>
<id>...</id>
<title>...</title>
</book>
</written-books>
</author>
</authors>
<book>
</books>
我现在所做的是使用 boolean 值来找出我们在哪些部分(书籍、引用资料、作者、成书)。我在开始/结束元素事件上执行此操作,然后在字符事件上我检查
if (qName.equals("id"){
if (writtenBooks){
}else if (authors){
}else if (references){
}else{
}
}else if ("title")...
但是好像不太优雅。有更好的解决方案吗?
最佳答案
根据我的理解,您要做的是读取 XML,然后对其进行处理。 (检查元素是否存在等)您可以使用 Apache Axiom 读取 xml 文件并轻松获取内容。然后你可以根据需要进行处理。我将放一个示例代码段来使用 AXIOM 获取 xml 文件的内容。
//read the xml file
StAXOMBuilder builder = new StAXOMBuilder(xmlStreamReader);
OMElement endPointElem = builder.getDocumentElement();
// go though the xml elemetns and do whatever you want
Iterator children = endPointElem.getChildElements();
while (children.hasNext()) {
........................
.......
}
关于java - 使用 [java] sax 读取 xml 文件的最佳算法/模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19921175/