⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch06_04.htm

📁 Perl & XML. by Erik T. Ray and Jason McIntosh ISBN 0-596-00205-X First Edition, published April
💻 HTM
字号:
<html><head><title>XML::SimpleObject (Perl and XML)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Erik T. Ray and Jason McIntosh" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="059600205XL" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Perl and XML" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#ffffff"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl &amp; XML" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch06_03.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228" /><td align="right" valign="top" width="228"><a href="ch06_05.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">6.4. XML::SimpleObject</h2><p>Using<a name="INDEX-501" /> built-in data types is fine, but as yourcode becomes more complex and hard to read, you may start to pine forthe neater interfaces of objects. Doing things like testing anode's type, getting the last child of an element,or changing the representation of data without breaking the rest ofthe program is easier with objects. It's notsurprising that there are more object-oriented modules for XML thanyou can shake a stick at.</p><p>Dan <a name="INDEX-502" />Brian's<tt class="literal">XML::SimpleObject</tt> starts the tour of object modelsfor XML trees. It takes the structure returned by<tt class="literal">XML::Parser</tt> in tree mode and changes it from ahierarchy of lists into a hierarchy of objects. Each objectrepresents an element and provides methods to access its children. Aswith <tt class="literal">XML::Simple</tt>, elements are accessed by theirnames, passed as arguments to the methods.</p><p>Let's see how useful this module is. <a href="ch06_04.htm#perlxml-CHP-6-EX-5">Example 6-5</a> is a silly datafile representing agenealogical tree. We're going to write a program toparse this file into an object tree and then traverse the tree toprint out a text description.</p><a name="perlxml-CHP-6-EX-5" /><div class="example"><h4 class="objtitle">Example 6-5. A genealogical tree </h4><blockquote><pre class="code">&lt;ancestry&gt;  &lt;ancestor&gt;&lt;name&gt;Glook the Magnificent&lt;/name&gt;    &lt;children&gt;      &lt;ancestor&gt;&lt;name&gt;Glimshaw the Brave&lt;/name&gt;&lt;/ancestor&gt;      &lt;ancestor&gt;&lt;name&gt;Gelbar the Strong&lt;/name&gt;&lt;/ancestor&gt;      &lt;ancestor&gt;&lt;name&gt;Glurko the Healthy&lt;/name&gt;        &lt;children&gt;          &lt;ancestor&gt;&lt;name&gt;Glurff the Sturdy&lt;/name&gt;&lt;/ancestor&gt;          &lt;ancestor&gt;&lt;name&gt;Glug the Strange&lt;/name&gt;            &lt;children&gt;              &lt;ancestor&gt;&lt;name&gt;Blug the Insane&lt;/name&gt;&lt;/ancestor&gt;              &lt;ancestor&gt;&lt;name&gt;Flug the Disturbed&lt;/name&gt;&lt;/ancestor&gt;            &lt;/children&gt;          &lt;/ancestor&gt;        &lt;/children&gt;      &lt;/ancestor&gt;    &lt;/children&gt;  &lt;/ancestor&gt;&lt;/ancestry&gt;</pre></blockquote></div><p><a href="ch06_04.htm#perlxml-CHP-6-EX-6">Example 6-6</a> is our program. It starts by parsing thefile with <tt class="literal">XML::Parser</tt> in tree mode and passing theresult to an <tt class="literal">XML::SimpleObject</tt> constructor. Next,we write a routine <tt class="literal">begat( )</tt> to traverse the treeand output text recursively. At each ancestor, it prints the name. Ifthere are progeny, which we find out by testing whether the<tt class="literal">child</tt> method returns anon-<tt class="literal">undef</tt> value, it descends the tree to processthem too.</p><a name="perlxml-CHP-6-EX-6" /><div class="example"><h4 class="objtitle">Example 6-6. An XML::SimpleObject program </h4><blockquote><pre class="code">use XML::Parser;use XML::SimpleObject;# parse the data file and build a tree objectmy $file = shift @ARGV;my $parser = XML::Parser-&gt;new( ErrorContext =&gt; 2, Style =&gt; "Tree" );my $tree = XML::SimpleObject-&gt;new( $parser-&gt;parsefile( $file ));# output a text descriptionprint "My ancestry starts with ";begat( $tree-&gt;child( 'ancestry' )-&gt;child( 'ancestor' ), '' );# describe a generation of ancestrysub begat {    my( $anc, $indent ) = @_;    # output the ancestor's name    print $indent . $anc-&gt;child( 'name' )-&gt;value;    # if there are children, recurse over them    if( $anc-&gt;child( 'children' ) and $anc-&gt;child( 'children' )-&gt;children ) {        print " who begat...\n";        my @children = $anc-&gt;child( 'children' )-&gt;children;        foreach my $child ( @children ) {            begat( $child, $indent . '   ' );        }    } else {        print "\n";    }}</pre></blockquote></div><p>To prove it works, here's the output. In theprogram, we added indentation to show the descent throughgenerations:</p><blockquote><pre class="code">My ancestry starts with Glook the Magnificent who begat...   Glimshaw the Brave   Gelbar the Strong   Glurko the Healthy who begat...      Glurff the Sturdy      Glug the Strange who begat...         Blug the Insane         Flug the Disturbed</pre></blockquote><p>We used several different methods to access data in objects.<tt class="literal">child( )</tt><a name="INDEX-503" /> returns a reference to an<tt class="literal">XML::SimpleObject</tt> object that represents a childof the source node. <tt class="literal">children()</tt><a name="INDEX-504" /> returns a list of such references.<tt class="literal">value( )</tt> looks for a character data node insidethe source node and returns a scalar value. Passing arguments inthese methods restricts the search to just a few matching nodes. Forexample, <tt class="literal">child( 'name' )</tt> specifies the<tt class="literal">&lt;name&gt;</tt> element among a set of children. Ifthe search fails, the value <tt class="literal">undef</tt> is given.</p><p>This is a good start, but as its name suggests, it may be a littletoo simple for some applications. There are limited ways to accessnodes, mostly by getting a child or list of children. Accessingelements by name doesn't work when more than oneelement has the same name.</p><p>Unfortunately, this module's objects lack a way toget XML back out, so outputting a document from this structure is noteasy. However, for simplicity, this module is an easy OO<a name="INDEX-505" /> solutionto<a name="INDEX-506" /><a name="INDEX-507" />learn and use.</p><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch06_03.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img alt="Home" border="0" src="../gifs/txthome.gif" /></a></td><td align="right" valign="top" width="228"><a href="ch06_05.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">6.3. XML::Parser's Tree Mode</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img alt="Book Index" border="0" src="../gifs/index.gif" /></a></td><td align="right" valign="top" width="228">6.5. XML::TreeBuilder</td></tr></table></div><hr width="684" align="left" /><img alt="Library Navigation Links" border="0" src="../gifs/navbar.gif" usemap="#library-map" /><p><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"><area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map></body></html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -