【发布时间】:2014-02-24 15:05:55
【问题描述】:
我正在尝试解析 xml 文档的一些特定部分。我正在考虑将数据从分析部分中提取出来,我需要警告、错误、通过,并且我需要进入每个部分 () 并获取结果和结果级别以及例如此“错误”中的文本我需要获取错误级别和文本“错误”。
<document>
<configuration>
</configuration>
<data>
</data>
<analysis warnings="5" errors="3" information="0" passed="false">
<files>
</files>
<results>
<form>
<section number="0">
<result level="error">ERROR</result>
<result level="error">ERROR</result>
<result level="error">ERROR</result>
<result level="warning">Warning</result>
<result level="warning">Warning</result>
</section>
<section number="1">
<result level="warning">WARNING</result>
</section>
<section number="2">
<result level="warning">WARNING</result>
<result level="warning">WARNING</result>
</section>
</form>
</results>
</analysis>
</document>
我有以下代码:
public void ProcessXMLFromPath(String path) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path);
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
System.out.println(node.getAttributes().toString());
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node cNode = childNodes.item(j);
if (cNode instanceof Element) {
System.out.println(cNode.getNodeName().toString());
if(cNode.getNodeName().toString() == "analysis")
{
String content = cNode.getLastChild().getTextContent().trim();
System.out.println(content);
//I thought this would print the children under the analysis section to the screen but I was mistaken. It does however make it to this point.
}
}
}
}
}
}
我要打印到控制台的唯一内容是:
configuration
data
analysis
任何帮助将不胜感激!
【问题讨论】:
标签: java parsing xml-parsing