如何通过DOM访问xml中的最低级子节点

时间:2012-08-05 09:43:03

标签: java xml dom

我有xml级节点,如:

<matrix1>
  <row1>
    <column>679</column>
    <column>9</column>
  </row2>
  <row2>
    <column>78</column>
    <column>29</column>
  </row2>
<matrix1> 

我在这里看到很多类似的东西,但不是更像这样的级别子节点, 我可以在解析过程后在DOM中跳过父节点直接访问<column>679</column>吗?或者将每个级别迭代到最低的子级以获得数值? 谢谢你有时间帮忙。

1 个答案:

答案 0 :(得分:0)

这里可能需要XPath表达式。无论文档使用何种模式,您都可以选择文档中的列节点:

//column

这是一个工作片段:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(____your XML InputStream____);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//column");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

检查Java XPath API以获取更多信息。

您还应该检查XML输入的语法。 matrix1和row1没有结束标记,这里是更正的XML:

<matrix1>
    <row1>
        <column>679</column>
        <column>9</column>
    </row1>
    <row2>
        <column>78</column>
        <column>29</column>
    </row2>
</matrix1>