This discussion is archived
6 Replies Latest reply: May 11, 2009 11:59 AM by DrClap RSS

Cannot Read Value from an XML Element

843789 Newbie
Currently Being Moderated
        try
        {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("simple2.xml"));

            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " +
                 doc.getDocumentElement().getNodeName());

            NodeList nl = doc.getElementsByTagName("channel");
            Node channel = nl.item(0);

            NodeList channel_child = channel.getChildNodes();

               for (int s = 0; s!=channel_child.getLength(); s++)
               {
                    Node cc1 = channel_child.item(s);

                    if (cc1.getNodeType() == Node.ELEMENT_NODE)
                    {
                         Element e1 = (Element) cc1;
                         System.out.print(e1.getNodeName()+":");
                         System.out.println(e1.getNodeValue());

                         if(e1.getNodeName().equals("image") || e1.getNodeName().equals("item"))
                         {
                              NodeList nl2 = doc.getElementsByTagName(e1.getNodeName());
                              Node image = nl2.item(0);
                              NodeList image_child = image.getChildNodes();

                              for (int x = 0; x!=image_child.getLength(); x++)
                              {
                                   Node ccx = image_child.item(x);
                                   if (ccx.getNodeType() == Node.ELEMENT_NODE)
                                   {
                                        Element e2 = (Element) ccx;
                                        System.out.print("\t"+e2.getNodeName()+":");
                                        System.out.println(e2.getNodeValue());
                                   }
                              }
                         }
                    }
               }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://weather.yahooapis.com/ns/rss/1.0"
 xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
   <title>Yahoo! Weather - Sunnyvale, CA</title>
   <link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/
   *http://weather.yahoo.com/forecast/94089_f.html</link>
   <description>Yahoo! Weather for Sunnyvale, CA</description>
   <language>en-us</language>
   <lastBuildDate>Tue, 29 Nov 2005 3:56 pm PST</lastBuildDate>
   <ttl>60</ttl>
   <yweather:location city="Sunnyvale" region="CA" country="US"></yweather:location>
   <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"></yweather:units>
   <yweather:wind chill="57" direction="350" speed="7"></yweather:wind>
   <yweather:atmosphere humidity="93" visibility="1609" pressure="30.12" rising="0"></yweather:atmosphere>
   <yweather:astronomy sunrise="7:02 am" sunset="4:51 pm"></yweather:astronomy>
   <image>
      <title>Yahoo! Weather</title>
      <width>142</width>
      <height>18</height>
      <link>http://weather.yahoo.com/</link>
      <url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url>
   </image>
   <item>
      <title>Conditions for Sunnyvale, CA at 3:56 pm PST</title>
      <geo:lat>37.39</geo:lat>
      <geo:long>-122.03</geo:long>
      <link>http://us.rd.yahoo.com/dailynews/rss/weather/
       Sunnyvale__CA/*
       http://weather.yahoo.com/ forecast/94089_f.html
      </link>
      <pubDate>Tue, 29 Nov 2005 3:56 pm PST</pubDate>
      <yweather:condition text="Mostly Cloudy" code="26" temp="57" date="Tue, 29 Nov 2005 3:56
          pm PST"></yweather:condition>
      <description><![CDATA[
 <img src="http://l.yimg.com/a/i/us/we/52/26.gif" /><br />
 <b>Current Conditions:</b><br />
 Mostly Cloudy, 57 F<p />
 <b>Forecast:</b><BR />
  Tue - Mostly Cloudy. High: 62 Low: 45<br />
  Wed - Mostly Cloudy. High: 60 Low: 52<br />
  Thu - Rain. High: 61 Low: 46<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/94089_f.html">Full Forecast at Yahoo! Weather</a><BR/>
 (provided by The Weather Channel)<br/>]]>
      </description>
      <yweather:forecast day="Tue" date="29 Nov 2005" low="45" high="62" text="Mostly Cloudy"
          code="27"></yweather:forecast>
      <yweather:forecast day="Wed" date="30 Nov 2005" low="52" high="60" text="Mostly Cloudy"
          code="28"></yweather:forecast>
      <guid isPermaLink="false">94089_2005_11_29_15_56_PST</guid>
   </item>
</channel>
</rss>
when i run the code i am able to read all the node names but not their values. It is showing null.
where am i going wrong ?
  • 1. Re: Cannot Read Value from an XML Element
    843789 Newbie
    Currently Being Moderated
    More_Milestone wrote:
    try
    {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("simple2.xml"));
    
    doc.getDocumentElement ().normalize ();
    System.out.println ("Root element of the doc is " +
    doc.getDocumentElement().getNodeName());
    
    NodeList nl = doc.getElementsByTagName("channel");
    Node channel = nl.item(0);
    
    NodeList channel_child = channel.getChildNodes();
    
                   for (int s = 0; s!=channel_child.getLength(); s++)
                   {
                        Node cc1 = channel_child.item(s);
    
                        if (cc1.getNodeType() == Node.ELEMENT_NODE)
                        {
                             Element e1 = (Element) cc1;
                             System.out.print(e1.getNodeName()+":");
                             System.out.println(e1.getNodeValue());
    
                             if(e1.getNodeName().equals("image") || e1.getNodeName().equals("item"))
                             {
                                  NodeList nl2 = doc.getElementsByTagName(e1.getNodeName());
                                  Node image = nl2.item(0);
                                  NodeList image_child = image.getChildNodes();
    
                                  for (int x = 0; x!=image_child.getLength(); x++)
                                  {
                                       Node ccx = image_child.item(x);
                                       if (ccx.getNodeType() == Node.ELEMENT_NODE)
                                       {
                                            Element e2 = (Element) ccx;
                                            System.out.print("\t"+e2.getNodeName()+":");
                                            System.out.println(e2.getNodeValue());
                                       }
                                  }
                             }
                        }
                   }
    }
    catch(Exception e)
    {
    System.out.println(e);
    }
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    <rss version="2.0" xmlns:yweather="http://weather.yahooapis.com/ns/rss/1.0"
    xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <channel>
    <title>Yahoo! Weather - Sunnyvale, CA</title>
    <link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/
    *http://weather.yahoo.com/forecast/94089_f.html</link>
    <description>Yahoo! Weather for Sunnyvale, CA</description>
    <language>en-us</language>
    <lastBuildDate>Tue, 29 Nov 2005 3:56 pm PST</lastBuildDate>
    <ttl>60</ttl>
    <yweather:location city="Sunnyvale" region="CA" country="US"></yweather:location>
    <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"></yweather:units>
    <yweather:wind chill="57" direction="350" speed="7"></yweather:wind>
    <yweather:atmosphere humidity="93" visibility="1609" pressure="30.12" rising="0"></yweather:atmosphere>
    <yweather:astronomy sunrise="7:02 am" sunset="4:51 pm"></yweather:astronomy>
    <image>
    <title>Yahoo! Weather</title>
    <width>142</width>
    <height>18</height>
    <link>http://weather.yahoo.com/</link>
    <url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url>
    </image>
    <item>
    <title>Conditions for Sunnyvale, CA at 3:56 pm PST</title>
    <geo:lat>37.39</geo:lat>
    <geo:long>-122.03</geo:long>
    <link>http://us.rd.yahoo.com/dailynews/rss/weather/
    Sunnyvale__CA/*
    http://weather.yahoo.com/ forecast/94089_f.html
    </link>
    <pubDate>Tue, 29 Nov 2005 3:56 pm PST</pubDate>
    <yweather:condition text="Mostly Cloudy" code="26" temp="57" date="Tue, 29 Nov 2005 3:56
    pm PST"></yweather:condition>
    <description><![CDATA[
    <img src="http://l.yimg.com/a/i/us/we/52/26.gif" /><br />
    <b>Current Conditions:</b><br />
    Mostly Cloudy, 57 F<p />
    <b>Forecast:</b><BR />
    Tue - Mostly Cloudy. High: 62 Low: 45<br />
    Wed - Mostly Cloudy. High: 60 Low: 52<br />
    Thu - Rain. High: 61 Low: 46<br />
    <br />
    <a href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/94089_f.html">Full Forecast at Yahoo! Weather</a><BR/>
    (provided by The Weather Channel)<br/>]]>
    </description>
    <yweather:forecast day="Tue" date="29 Nov 2005" low="45" high="62" text="Mostly Cloudy"
    code="27"></yweather:forecast>
    <yweather:forecast day="Wed" date="30 Nov 2005" low="52" high="60" text="Mostly Cloudy"
    code="28"></yweather:forecast>
    <guid isPermaLink="false">94089_2005_11_29_15_56_PST</guid>
    </item>
    </channel>
    </rss>
    when i run the code i am able to read all the node names but not their values. It is showing null.
    where am i going wrong ?
    I admittedly haven't taken the time to read through all of your code, but I'm willing to be that this is your mistake:
    the following node actually has a child node:
    <example>this is a test</example>
    So if, for example, you were to use an XPath statement to select your "example" node, you'd have to get the first child node's value ..., example:
    Node node = (Node)xpath.evaluate("/example", XPathConstants.NODE);
    String value = node.getChildNodes().item(0).getNodeValue();
    Don't recall the API off the top of my head, so some of those signatures may be off, but that explains the gist of it.
  • 2. Re: Cannot Read Value from an XML Element
    843789 Newbie
    Currently Being Moderated
    sorry i don't want to use xpath.
    i haven't used it before.
  • 3. Re: Cannot Read Value from an XML Element
    DrClap Expert
    Currently Being Moderated
    You just have the naive assumption that the "value" of an Element node should be the text contained in its Text child or children. That isn't the case. Read the API documentation for the Node interface to see what getValue() actually returns.

    And I agree with NavyCoder. The world doesn't need another 200 lines of DOM-whacking code. Learn about XPath and you won't have to do it any more.
  • 4. Re: Cannot Read Value from an XML Element
    843789 Newbie
    Currently Being Moderated
    More_Milestone wrote:
    sorry i don't want to use xpath.
    i haven't used it before.
    I've no need to drive a car as my donkey-cart works just fine, and I've never driven before.
  • 5. Re: Cannot Read Value from an XML Element
    843789 Newbie
    Currently Being Moderated
    Encephalopathic wrote:
    More_Milestone wrote:
    sorry i don't want to use xpath.
    i haven't used it before.
    I've no need to drive a car as my donkey-cart works just fine, and I've never driven before.
    Liar.
  • 6. Re: Cannot Read Value from an XML Element
    843789 Newbie
    Currently Being Moderated
    Navy_Coder wrote:
    Liar.
    OK, OK, it's an @ss-cart.