简体   繁体   中英

using SAX parser, how do you parse an xml file in java

Is it possible to give path expressions in SAX parser? I have an XML file which has a few same name tags, but they are in different element. Is there any way to differentiate between them. Here is the XML:

<report id="322077">
        <update>
          <when>1136117311</when>
          <what>nobody@mozilla.org</what>
        </update>
        <update>
          <when>1136117422</when>
          <what>asqueella@gmail.com</what>
        </update>
      </report>
    <report id="322074">
        <update>
          <when>1136117311</when>
          <what>nobody@mozilla.org</what>
        </update>
        <update>
          <when>1136117422</when>
          <what>asqueella@gmail.com</what>
        </update>
      </report>
    <report id="322076">
        <update>
          <when>1136117311</when>
          <what>nobody@mozilla.org</what>
        </update>
        <update>
          <when>1136117422</when>
          <what>asqueella@gmail.com</what>
        </update>
      </report>
String xml= // your xml
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
String expression="//update"; // See XPath
XPathExpression expr = xpath.compile(expression) ; 
    NodeList nodes  = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int k = 0; k < nodes.getLength(); k++) {
// Do what you want with that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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