我正在尝试解析xml doc的一些特定部分。我正在考虑从分析部分提取数据,我需要警告,错误,传递,我需要进入每个部分()并获得结果和结果级别和文本例如在这个“错误”中我需要获得错误级别和文本“ERROR”。
<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
任何帮助将不胜感激!
答案 0 :(得分:1)
代码的几个问题:
cNode.getNodeName().toString() == "analysis"
,与.equals
analysis
是document
的直接后代(根据我们这里的xml部分),因此必须尽早检查。您的代码会在level 3
而不是2
results
,form
和text
节点。修改强> 基于注释,在没有多个for循环的情况下遍历的有效方法是递归,如下所示:
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
InputStream path = new FileInputStream("sample.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(path);
traverse(document.getDocumentElement());
}
public static void traverse(Node node) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node currentNode = list.item(i);
traverse(currentNode);
}
if (node.getNodeName().equals("result")) {
System.out.println("This -> " + node.getTextContent());
}
}
这将结果显示为:
This -> ERROR
This -> ERROR
This -> ERROR
This -> Warning
This -> Warning
This -> WARNING
This -> WARNING
This -> WARNING
答案 1 :(得分:0)
对于这三个中的每一个(configuration
,data
,analysis
),获取他们的子节点并向下钻取,直至找到错误(即result
标签)。您可以在analysis
下方找到这些内容(但不会直接位于其下方)。因此,您可以向下钻取analysis
。