3

I want to use the Java XmlPullParser to parse an XML file like this:

<start>
    <tag1> text1 </tag1>
    <tag2> 
        <tag3>text3</tag3>
        <tag1>text4</tag1>
    </tag2>
    <tag4> text5</tag4>
</start>

I want only <tag1> text1 </tag1> as the result. My current method produces both <tag1> text1 </tag1> and <tag1>text4<tag1/>. What else must I do?

Edit:

I am getting the XML in String format. I want to parse it using org.xmlpull.v1.XmlPullParser;.

Pops
  • 30,199
  • 37
  • 136
  • 151
Romi
  • 4,833
  • 28
  • 81
  • 113
  • 1
    In the future, if you have a specific requirement (including but not limited to a particular parser), please mention it in the first draft of your question. – Pops Nov 18 '11 at 22:25

4 Answers4

9

You could also just use the javax.xml.xpath APIs:

import java.io.FileReader;
import javax.xml.xpath.*;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class XPathDemo {

    public static void main(String[] args) throws Exception {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        InputSource xml = new InputSource(new FileReader("input.xml"));
        Node result = (Node) xpath.evaluate("/tag1", xml, XPathConstants.NODE);
        System.out.println(result);
    }

}
bdoughan
  • 147,609
  • 23
  • 300
  • 400
5

Everyone has thier own preferences for XML processing in Java and my preference is to use JAXB when dealing with XML in Java because I find it easier to use that straight xpath.

ChadNC
  • 2,528
  • 4
  • 25
  • 39
  • I would still use JAXB with the only difference being that I would use a transform to save the xml string as an xml file then unmarshall the file into a Java object using JAXB and then get what I wanted from the object. – ChadNC Nov 07 '11 at 13:35
1

You can do that using Java Xpath API

hovanessyan
  • 30,580
  • 6
  • 55
  • 83
0

try to use dom4j library

    InputStream is = FileUtils.class.getResourceAsStream(filepath);
    SAXReader reader = new SAXReader();
    org.dom4j.Document doc = reader.read(is);
    is.close();
    Element content = doc.getRootElement();
    List<Element> els = content.elements("elemeNtname");

after this in method you will get in els list all the elements in xml file with name "elemeNtname".

shift66
  • 11,760
  • 13
  • 50
  • 83