Difference between revisions of "Ruby:Read XML"

From Progzoo
Jump to: navigation, search
Line 12: Line 12:
 
</world>
 
</world>
 
</pre></div>
 
</pre></div>
<prog>
+
<prog>require 'rexml/document'
require 'rexml/document'
 
 
doc = REXML::Document.new File.new('bbc.xml')
 
doc = REXML::Document.new File.new('bbc.xml')
node = REXML::XPath.first(doc,"//country[@id='fr']/@pop")
+
nl  = doc.elements.to_a("//country")
print node.value
+
e  = nl[0]
 +
print e.attribute("pop").value
 
</prog>
 
</prog>
 
<p>
 
<p>
You load the XML file via the DocumentBuilderFactory, DocumentBuilder
+
The REXML library allows an XPath expression such as <code>//country</code> to be used in place of the DOM methods "getElementsByTagName"
and parser. You then obtain a list of all country nodes. The first node
 
represents Germany, it must be cast as an element before you can access the
 
pop attribute.
 
 
</p>
 
</p>
 
<p>The value returned should be 82 million.</p>
 
<p>The value returned should be 82 million.</p>
 
</question>
 
</question>

Revision as of 17:57, 31 December 2007

The file http://progzoo.net/bbc.xml is as shown:
<world>
 <region id='Europe'>
  <country id='de' name='Germany' pop='82000000'/>
  <country id='fr' name='France'  pop='60000000'/>
 </region>
 <region id='Asia'>
  <country id='cn' name='China' pop='1300000000'/>
 </region>
</world>

The REXML library allows an XPath expression such as //country to be used in place of the DOM methods "getElementsByTagName"

The value returned should be 82 million.

[Font] [Default] [Show] [Resize] [History] [Profile]