在 Java 中使用 DOM 进行 XML 解析 [英] XML parsing using DOM in java
本文介绍了在 Java 中使用 DOM 进行 XML 解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<tree>
<declarations>
<attributeDecl name="name" type="String"/>
</declarations>
<branch>
<attribute name="name" value="Malaria"/>
<branch>
<attribute name="name" value="Excess Stool"/>
<branch>
<attribute name="name" value="Do you have watery stool"/>
<branch>
</branch>
<attribute name="name" value="Do you have this condition for more than a weeks time"/>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="High Fever"/>
<branch>
<attribute name="name" value="Was your peak temperature greater than 104"/>
<branch>
<attribute name="name" value="Do you have high fever for more than a weeks time "/>
<branch>
<attribute name="name" value="Do you have chills"/>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="Bodyache"/>
<branch>
<attribute name="name" value="Do you have pain in the left part of the head "/>
<branch>
<attribute name="name" value="Do you have headache more than 5 times a day "/>
<branch>
<attribute name="name" value="Duration of the headache spans for more than a day "/>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
<branch>
<attribute name="name" value="No"/>
</branch>
</branch>
</branch>
</tree>
我必须解析这个 xml.我使用 DOM 解析器来解析相同的.因为在这种情况下属性名称始终是名称,我对如何解析 xml 有点无能为力.
I have to parse this xml .I am using DOM parser to parse the same .Since attribute name is always name in this case , i am bit clueless as in how to parse the xml .
推荐答案
从以下示例中获取帮助
public class DOMParser {
private Document doc = null;
public DOMParser() {
try {
doc = parserXML(new File("resource/data.xml"));
visit(doc, 0);
} catch (Exception error) {
error.printStackTrace();
}
}
public void visit(Node node, int level) {
NodeList nl = node.getChildNodes();
for (int i = 0, cnt = nl.getLength(); i < cnt; i++) {
if (nl.item(i).hasAttributes()) {
printAttributes(nl.item(i));
}
visit(nl.item(i), level + 1);
}
}
public Document parserXML(File file) throws SAXException, IOException,
ParserConfigurationException {
return DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(file);
}
public static void main(String[] args) {
new DOMParser();
}
private void printAttributes(Node node) {
NamedNodeMap attrs = node.getAttributes();
System.out.print(node.getNodeName());
for (int i = 0; i < attrs.getLength(); i++) {
Attr attribute = (Attr) attrs.item(i);
System.out.print(" : " + attribute.getName() + "="
+ attribute.getValue());
}
System.out.println("");
}
}
这篇关于在 Java 中使用 DOM 进行 XML 解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文