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;.

1
  • 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. Commented Nov 18, 2011 at 22:25

4 Answers 4

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);
    }

}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.
1

You can do that using Java Xpath API

Comments

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.