1

I try to parse a xml-feed with the follow data:

<company>
<year id="2000">
<quarter id="1" sales="80"/>
</year>

<year id="2001">
<quarter id="1" sales="20"/>
</year>
</company>

Is it possible to get only the year with the value 2001?

I have the follow code:

URL url = new URL(feedUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
     InputStream is = conn.getInputStream();

     //DocumentBuilderFactory, DocumentBuilder are used for 
     //xml parsing
     DocumentBuilderFactory dbf = DocumentBuilderFactory
       .newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();

     //using db (Document Builder) parse xml data and assign
     //it to Element
     Document document = db.parse(is);
     Element element = document.getDocumentElement();

     //take rss nodes to NodeList
     element.normalize();
     NodeList nodeList =  ???????
Johan
  • 51
  • 6

2 Answers2

3

You can use the XPath APIs:

import java.io.StringReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xml = "<company><year id='2000'><quarter id='1' sales='80'/></year><year id='2001'><quarter id='1' sales='20'/></year></company>";
        String xpath = "/company/year[@id=2001]";
        XPath xPath = XPathFactory.newInstance().newXPath();
        Node node = (Node) xPath.evaluate(xpath, new InputSource(new StringReader(xml)), XPathConstants.NODE);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(node), new StreamResult(System.out));
    }

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

If you don't want to use XPath, you can do this:

  NodeList list = element.getElementsByTagName("year");
  for(int i = 0 ; i < list.getLength(); i++){
      Node n = list.item(i);
      NamedNodeMap map = n.getAttributes();
      String value = map.getNamedItem("id").getNodeValue();
      System.out.println(value);
      if("2001".equals(value)){
          //do something with node n
          System.out.println("found");
      }          
  }
dogbane
  • 266,786
  • 75
  • 396
  • 414