简体   繁体   English

在JAVA中如何跳到XML中的特定节点?

[英]in JAVA how to jump to particular node in XML?

I have xml having data something like this 我有XML具有这样的数据

<A Name="">
</A>
<A Name="">
</A>
.....

How can i jump to some particular node and read it - like 3rd tag- A by using SAX parser 如何使用SAX解析器跳转到某个特定节点并读取它-如第3个标签-A

If you want to jump to a sub-node you must use the DOM API and not SAX. 如果要跳转到子节点,则必须使用DOM API而不是SAX。

  // load the document
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder(); 
  Document doc = db.parse(new File(filename));

  // prepare result list
  ArrayList<Element> res = new ArrayList<Element>();

  // prepare to use xpath
  XPath xpath = XPathFactory.newInstance().newXPath();
  // read 3rd A element
  NodeList list = (NodeList) xpath.compile("/A[3]")
      .evaluate(doc, XPathConstants.NODESET);

  // copy the DOM element in the result list
  for (int i = 0; i < list.getLength(); i++) {
    res.add((Element) list.item(i));
  }

Please note that contrary to SAX it will read the whole document before allowing you to access it. 请注意,与SAX相反,它将在允许您访问之前阅读整个文档。

You cannot jump to (skip all elements before) a certain element using SAX. 您不能使用SAX跳到(跳过所有元素)某个元素。 It reads sequentially all elements and returns them to your ContentHandler . 它顺序读取所有元素,并将它们返回给ContentHandler All you can do, is skip the parsing, after you found the relevant element by throwing an exception from within the ContentHandler. 找到所有相关元素之后,可以通过在ContentHandler中引发异常来跳过分析。

If you're looking for a kind of random access to the XML elements, then you should definitively consider DOM as pointed out by @Guillaume. 如果您正在寻找一种对XML元素的随机访问,那么您应该明确地考虑@Guillaume指出的DOM。

You can "jump" to a particular XML tag, but reading the tags in sequence. 您可以“跳转”到特定的XML标签,但是要按顺序读取标签。 There is no reliable way to skip tags without reading. 没有可靠的方法来跳过标签而不阅读。

Your best off using the Java StAX API. 最好使用Java StAX API。 The Oracle Java Tutorial Site has a great read on how to work with it. Oracle Java Tutorial Site对如何使用它有很好的阅读。 It's very clean and simple for doing basic read/parse from XML. 从XML进行基本的读取/解析非常干净和简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM