3

我们可以使用 dom 解析器在 xml 文件中按 id 搜索元素吗,例如:

<root>
  <context id="one">
    <entity>
      <identifier>new one</identifier>
    </entity>
  </context>

  <context id="two">
    <entity>
      <identifier>second one</identifier>
    </entity>
  </context>

</root>

我想要一个 id = "one" 的节点,我的代码

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("filename.xml"));

Element ele = document.getElementById("one");

返回空值,

还有其他方法吗?

4

4 回答 4

3

您可以使用javax.xml.xpathJDK/JRE 中的 API 通过 XPath 查找元素。

例子

import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new File("filename.xml"));

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Element element = (Element) xpath.evaluate("//*[@id='one']", document, XPathConstants.NODE);
    }

}
于 2013-06-21T12:13:55.817 回答
3

From the documentation for Document.getElementById

Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.

The problem is the Document doesn't know that an attribute called id is an identifier unless you tell it. You need to set a schema on the DocumentBuilderFactory before you call newDocumentBuilder. That way the DocumentBuilder will be aware of the element types.

In the schema you will need something like this in the appropriate place:

<xs:attribute name="id" type="xs:ID"/> 
于 2013-06-21T12:03:23.587 回答
0

您可以改为使用Jsoup之类的第三方库,它可以很好地完成这项工作。

File input = new File("/tmp/input.xml");
Document doc = Jsoup.parse(input, "UTF-8", "test");

然后你可以使用这样的东西:

doc.select("context#id=one")

这是否回答你的问题?

于 2013-06-21T12:07:59.793 回答
0

尝试使用 XML - Xpath 表达式,这很容易

File fXmlFile = new File("filePath");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);


doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());


XPathFactory factory = XPathFactory.newInstance();

            XPath xpath = factory.newXPath();

            String expression;
            Node node;

            // 1. elements with id '1'
            expression = "//context[@id='one']"; 
            node = (Node ) xpath.evaluate(expression, doc, XPathConstants.NODE);
于 2016-04-07T06:37:45.067 回答