Michael
Michael

Reputation: 375

Read element inside element from XML in SAX or Dom

<rootNode>
    <Movies>
    <Movie id=1>
         <title> title1</title>
         <Actors>
            <Actor>Actor1</Actor>
            <Actor>Actor2</Actor>
         <Actors>
    </Movie>
    </Movies>
    <performers >
        <performer id=100>
             <name>name1</name>
             <movie idref=1/>
        </performer>
    </performers>
</rootNode>

Question1: I only want to get the movie under the movies. I tried both of DOM and SAX. It also returns the under performers. How can I avoid this by using SAX or DOM

DOM:
doc.getElementsByTagName("movie");
SAX:
public void startElement(String uri, String localName,String qName, 
                Attributes attributes) throws SAXException {

        if (qName.equalsIgnoreCase("movie")) 

Question2: How can I get the element inside element (Actor under movies) by using DOM or SAX?

Basically, what I want to do is output the data in order.

1,title, Actor1,Actor2
100,name1,1

Upvotes: 1

Views: 2058

Answers (2)

iagreen
iagreen

Reputation: 32016

XPath is designed for this type of extraction. For your example file, the query would be something like the following. For simplicity, I assumed your xml was in a res/raw, but in practice you will need to create the InputSource from where ever you are getting your xml.

    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "/rootNode/Movies/Movie";
    try {
        NodeList nodes = (NodeList) xpath.evaluate(expression, doc,XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
         e.printStackTrace();
    }

Upvotes: 0

Marcel St&#246;r
Marcel St&#246;r

Reputation: 23535

doc.getElementsByTagName("movies")[0].childNodes;

gets you all the movies/movie nodes (watch for lower-/upper-case!). See here http://www.w3schools.com/dom/dom_intro.asp for a short tutorial.

Upvotes: 2

Related Questions