Difference between revisions of "Ruby:Read XML"

From Progzoo
Jump to: navigation, search
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{{topTenTips}}
 
<question lang="rb" className="Demo" copyFile="bbc.xml">
 
<question lang="rb" className="Demo" copyFile="bbc.xml">
 
<div>The file http://progzoo.net/bbc.xml is as shown:
 
<div>The file http://progzoo.net/bbc.xml is as shown:
<pre style="width:80ex;border-style:solid;border-width:thin;">
+
<pre style="border-style:solid;border-width:thin;">
 
&lt;world&gt;
 
&lt;world&gt;
 
  &lt;region id='Europe'&gt;
 
  &lt;region id='Europe'&gt;
Line 12: Line 13:
 
&lt;/world&gt;
 
&lt;/world&gt;
 
</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>

Latest revision as of 22:28, 10 April 2008

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]