Sophie

Sophie

distrib > Fedora > 17 > i386 > media > updates > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 1822

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../doc/otp_doc.css" type="text/css">
<title>Erlang -- xmerl</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../../../../doc/js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../../../../doc/js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../../../../doc/erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="index.html">Reference Manual</a><br><a href="release_notes.html">Release Notes</a><br><a href="../pdf/xmerl-1.3.2.pdf">PDF</a><br><a href="../../../../doc/index.html">Top</a></small><p><strong>xmerl</strong><br><strong>User's Guide</strong><br><small>Version 1.3.2</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<ul class="flipMenu" imagepath="../../../../doc/js/flipmenu"><li id="loadscrollpos" title="xmerl" expanded="true">xmerl<ul>
<li><a href="xmerl_ug.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="xmerl_ug.html#id61226">Introduction</a></li>
<li title="xmerl User Interface Data Structure"><a href="xmerl_ug.html#id58000">xmerl User Interface Data Structure</a></li>
<li title="Getting Started"><a href="xmerl_ug.html#id61138">Getting Started</a></li>
<li title="Example: Extracting Data From XML Content"><a href="xmerl_ug.html#id60745">Example: Extracting Data From XML Content</a></li>
<li title="Example: Create XML Out Of Arbitrary Data"><a href="xmerl_ug.html#id61369">Example: Create XML Out Of Arbitrary Data</a></li>
<li title="Example: Transforming XML To HTML"><a href="xmerl_ug.html#id60061">Example: Transforming XML To HTML</a></li>
</ul>
</li></ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>1 xmerl</h1>
  

  <h3><a name="id61226">1.1 
        Introduction</a></h3>
    

    <h4>Features</h4>
      
      <p>The <strong>xmerl</strong> XML parser is able to parse XML documents
        according to the XML 1.0 standard. As default it performs
        well-formed parsing, (syntax checks and checks of well-formed
        constraints). Optionally one can also use xmerl as a validating
        parser, (validate according to referenced DTD and validating
        constraints). By means of for example the xmerl_xs module it is
        possible to transform the parsed result to other formats,
        e.g. text, HTML, XML etc.</p>
    

    <h4>Overview</h4>
      
      <p>This document does not give an introduction to XML. There
        are a lot of books available that describe XML from
        different views. At the <span class="bold_code"><a href="http://www.w3.org">www.W3.org</a></span> site you will find
        the <span class="bold_code"><a href="http://www.w3.org/TR/REC-xml/">XML 1.0 specification</a></span> and other related specs. One site were
        you can find tutorials on XML and related specs is <span class="bold_code"><a href="http://www.zvon.org">ZVON.org</a></span>.</p>
      <p>However, here you will find some examples of how to use
        and to what you can use xmerl. A detailed description of the
        user interface can be found in the reference manual.</p>
      <p>There are two known shortcomings in xmerl:</p>
      <ul>
        <li>It cannot retrieve external entities on the Internet
         by a URL reference, only resources in the local file
         system.</li>
        <li>xmerl can parse Unicode encoded data. But, it fails
         on tag names, attribute names and other mark-up names that
         are encoded Unicode characters not mapping on ASCII.</li>
      </ul>
      <p>By parsing an XML document you will get a record,
        displaying the structure of the document, as return
        value. The record also holds the data of the document. xmerl
        is convenient to use in for instance the following scenarios:</p>
      <p>You need to retrieve data from XML documents. Your
        Erlang software can handle information from the XML document
        by extracting data from the data structure received by
        parsing.</p>
      <p>It is also possible to do further processing of parsed
        XML with xmerl. If you want to change format of the XML
        document to for instance HTML, text or other XML format you
        can transform it. There is support for such transformations
        in xmerl.</p>
      <p>One may also convert arbitrary data to XML. So it for
        instance is easy to make it readable by humans. In this case
        you first create xmerl data structures out of your data, then
        transform it to XML. </p>
      <p>You can find examples of these three examples of usage
        below.</p>
    
  

  <h3><a name="id58000">1.2 
        xmerl User Interface Data Structure</a></h3>
    
    <p>The following records used by xmerl to save the parsed
      data are defined in <span class="code">xmerl.hrl</span></p>
    <p>The result of a successful parsing is a tuple
      <span class="code">{DataStructure,M}</span>. <span class="code">M</span> is the XML production Misc,
      which is the mark-up that comes after the element of the
      document. It is returned "as is". <span class="code">DataStructure</span> is an
      <span class="code">xmlElement</span> record, that among others have the fields
      <span class="code">name</span>, <span class="code">parents</span>, <span class="code">attributes</span> and
      <span class="code">content</span> like:</p>
    <div class="example"><pre>
#xmlElement{name=Name,
            ...
            parents=Parents,
            ...
            attributes=Attrs,
            content=Content,
            ...}    </pre></div>
    <p>The name of the element is found in the <span class="code">name</span>
      field. In the <span class="code">parents</span> field is the names of the parent
      elements saved. Parents is a list of tuples where the first
      element in each tuple is the name of the parent element. The
      list is in reverse order.</p>
    <p>The record <span class="code">xmlAttribute</span> holds the name and value of
      an attribute in the fields <span class="code">name</span> and <span class="code">value</span>. All
      attributes of an element is a list of xmlAttribute in the
      field <span class="code">attributes</span> of the xmlElement record.
      </p>
    <p>The <span class="code">content</span> field of the top element is a list of
      records that shows the structure and data of the document. If
      it is a simple document like: </p>
    <div class="example"><pre>
&lt;?xml version="1.0"?&gt;
&lt;dog&gt;
Grand Danois
&lt;/dog&gt;    </pre></div>
    <p>The parse result will be:</p>
    <div class="example"><pre>
#xmlElement{name = dog,
            ...
            parents = [],
            ...
            attributes = [],
            content = [{xmlText,[{dog,1}],1,[],"\
Grand Danois\
",text}],
            ...
            }    </pre></div>
    <p>Where the content of the top element is:
      <span class="code">[{xmlText,[{dog,1}],1,[],"\ Grand Danois\ ",text}]</span>. Text will be returned in <span class="code">xmlText</span> records. Though,
      usually documents are more complex, and the content of the top
      element will in that case be a nested structure with
      xmlElement records that in turn may have complex content. All of
      this reflects the structure of the XML document.</p>
    <p>Space characters between mark-up as <span class="code">space</span>,
      <span class="code">tab</span> and <span class="code">line feed</span> are normalized and returned as
      xmlText records.</p>

    <h4>Errors</h4>
      
      <p>An unsuccessful parse results in an error, which may be a
        tuple <span class="code">{error,Reason}</span> or an exit:
        <span class="code">{'EXIT',Reason}</span>. According to the XML 1.0 standard
        there are <span class="code">fatal error</span> and <span class="code">error</span> situations. The
        fatal errors <strong>must</strong> be detected by a conforming parser
        while an error <strong>may</strong> be detected. Both categories of
        errors are reported as fatal errors by this version of xmerl,
        most often as an exit.</p>
    
  

  <h3><a name="id61138">1.3 
        Getting Started</a></h3>
    
    <p>In the following examples we use the XML file
      "motorcycles.xml" and the corresponding DTD
      "motorcycles.dtd". motorcycles.xml looks like:
            <a name="motorcyclesxml"></a>
</p>
<div class="example"><pre>

&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;!DOCTYPE motorcycles SYSTEM "motorcycles.dtd"&gt;
&lt;motorcycles&gt;
  &lt;bike year="2000" color="black"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Suzuki&lt;/manufacturer&gt;
      &lt;brandName&gt;Suzuki VL 1500&lt;/brandName&gt;
      &lt;additionalName&gt;Intruder&lt;/additionalName&gt;
    &lt;/name&gt;
    &lt;engine&gt;V-engine, 2-cylinders, 1500 cc&lt;/engine&gt;
    &lt;kind&gt;custom&lt;/kind&gt;
    &lt;drive&gt;cardan&lt;/drive&gt;
    &lt;accessories&gt;Sissy bar, luggage carrier,V&amp;amp;H exhaust pipes&lt;/accessories&gt;
  &lt;/bike&gt;
  &lt;date&gt;2004.08.25&lt;/date&gt;
  &lt;bike year="1983" color="read pearl"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Yamaha&lt;/manufacturer&gt;
      &lt;brandName&gt;XJ 400&lt;/brandName&gt;
    &lt;/name&gt;
    &lt;engine&gt;4 cylinder, 400 cc&lt;/engine&gt;
    &lt;kind&gt;alround&lt;/kind&gt;
    &lt;drive&gt;chain&lt;/drive&gt;
    &lt;comment&gt;Good shape!&lt;/comment&gt;
  &lt;/bike&gt;
&lt;/motorcycles&gt;
</pre></div>    <p>and motorcycles.dtd looks like: </p>
<div class="example"><pre>

&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;!ELEMENT motorcycles (bike,date?)+ &gt;
&lt;!ELEMENT bike        (name,engine,kind,drive, accessories?,comment?) &gt;
&lt;!ELEMENT name        (manufacturer,brandName,additionalName?) &gt;
&lt;!ELEMENT manufacturer       (#PCDATA)&gt;
&lt;!ELEMENT brandName         (#PCDATA)&gt;
&lt;!ELEMENT additionalName    (#PCDATA)&gt;
&lt;!ELEMENT engine             (#PCDATA)&gt;
&lt;!ELEMENT kind               (#PCDATA)&gt;
&lt;!ELEMENT drive              (#PCDATA)&gt;
&lt;!ELEMENT comment            (#PCDATA)&gt;
&lt;!ELEMENT accessories        (#PCDATA)&gt;

&lt;!-- Date of the format yyyy.mm.dd --&gt;
&lt;!ELEMENT date              (#PCDATA)&gt;
&lt;!ATTLIST  bike year NMTOKEN #REQUIRED
                color NMTOKENS #REQUIRED
                condition (useless | bad | serviceable | moderate | good | excellent | new | outstanding) "excellent" &gt;
</pre></div>    <p>If you want to parse the XML file motorcycles.xml you run
      it in the Erlang shell like:</p>
    <div class="example"><pre>
3&gt; {ParsResult,Misc}=xmerl_scan:file("motorcycles.xml"). 
{{xmlElement,motorcycles,
             motorcycles,
             [],
             {xmlNamespace,[],[]},
             [],
             1,
             [],
             [{xmlText,[{motorcycles,1}],1,[],"\
  ",text},
              {xmlElement,bike,
                          bike,
                          [],
                          {xmlNamespace,[],[]},
                          [{motorcycles,1}],
                          2,
                          [{xmlAttribute,year,[],[],[],[]|...},
                           {xmlAttribute,color,[],[],[]|...}],
                          [{xmlText,[{bike,2},{motorcycles|...}],
                                    1,
                                    []|...},
                           {xmlElement,name,name,[]|...},
                           {xmlText,[{...}|...],3|...},
                           {xmlElement,engine|...},
                           {xmlText|...},
                           {...}|...],
                          [],
                          ".",
                          undeclared},
              ...
              ],
             [],
             ".",
             undeclared},
 []}
4&gt;     </pre></div>
    <p>If you instead receives the XML doc as a string you can
      parse it by <span class="code">xmerl_scan:string/1</span>. Both file/2 and string/2
      exists where the second argument is a list of options to the
      parser, see the <span class="bold_code"><a href="xmerl_scan.html">reference manual</a></span>.</p>
  

  <h3><a name="id60745">1.4 
        Example: Extracting Data From XML Content</a></h3>
    
    <p>In this example consider the situation where you want to
      examine a particular data in the XML file. For instance, you
      want to check for how long each motorcycle have been recorded.</p>
    <p>Take a look at the DTD and observe that the structure of an
      XML document that is conformant to this DTD must have one
      motorcycles element (the root element). The motorcycles element
      must have at least one bike element. After each bike element it
      may be a date element. The content of the date element is
      #PCDATA (Parsed Character DATA), i.e. raw text. Observe that if
      #PCDATA must have a <span class="code">"&lt;"</span> or a <span class="code">"&amp;"</span> character it must
      be written as <span class="code">"&amp;lt;"</span> and <span class="code">"&amp;amp;"</span>
      respectively. Also other character entities exists similar to
      the ones in HTML and SGML.</p>
    <p>If you successfully parse the XML file with the validation
      on as in:
      <span class="code">xmerl_scan:file('motorcycles.xml',[{validation,true}])</span>
      you know that the XML document is valid and has the structure
      according to the DTD.</p>
    <p>Thus, knowing the allowed structure it is easy to write a
      program that traverses the data structure and picks the
      information in the xmlElements records with name date.</p>
    <p>Observe that white space: each space, tab or line feed,
      between mark-up results in an xmlText record.</p>
    <p></p>
  

  <h3><a name="id61369">1.5 
        Example: Create XML Out Of Arbitrary Data</a></h3>
    
    <p>For this task there are more than one way to go. The "brute
      force" method is to create the records you need and feed your
      data in the content and attribute fields of the appropriate
      element.</p>
    <p>There is support for this in xmerl by the "simple-form"
      format. You can put your data in a simple-form data structure
      and feed it into
      <span class="code">xmerl:export_simple(Content,Callback,RootAttributes)</span>. Content
      may be a mixture of simple-form and xmerl records as xmlElement
      and xmlText.</p>
    <p>The Types are:</p>
    <ul>
      <li>Content = [Element]</li>
      <li>Callback = atom()</li>
      <li>RootAttributes = [Attributes]</li>
    </ul>
    <p>Element is any of:</p>
    <ul>
      <li>{Tag, Attributes, Content}</li>
      <li>{Tag, Content}</li>
      <li>Tag</li>
      <li>IOString</li>
      <li>#xmlText{}</li>
      <li>#xmlElement{}</li>
      <li>#xmlPI{}</li>
      <li>#xmlComment{}</li>
      <li>#xmlDecl{}</li>
    </ul>
    <p>The simple-form structure is any of <span class="code">{Tag, Attributes, Content}</span>, <span class="code">{Tag, Content}</span> or <span class="code">Tag</span> where:</p>
    <p></p>
    <ul>
      <li>Tag = atom()</li>
      <li>Attributes = [{Name, Value}| #xmlAttribute{}]</li>
      <li>Name = atom()</li>
      <li>Value = IOString | atom() | integer()</li>
    </ul>
    <p>See also reference manual for 
      <span class="bold_code"><a href="xmerl.html#export_simple-3">xmerl</a></span></p>
    <p>If you want to add the information about a black Harley
      Davidsson 1200 cc Sportster motorcycle from 2003 that is in
      shape as new in the motorcycles.xml document you can put the
      data in a simple-form data structure like:</p>
    <div class="example"><pre>
Data =
  {bike,
     [{year,"2003"},{color,"black"},{condition,"new"}],
     [{name,
         [{manufacturer,["Harley Davidsson"]},
          {brandName,["XL1200C"]},
          {additionalName,["Sportster"]}]},
      {engine,
         ["V-engine, 2-cylinders, 1200 cc"]},
      {kind,["custom"]},
      {drive,["belt"]}]}    </pre></div>
    <p>In order to append this data to the end of the
      motorcycles.xml document you have to parse the file and add Data
      to the end of the root element content.</p>
    <div class="example"><pre>
    {RootEl,Misc}=xmerl_scan:file('motorcycles.xml'),
    #xmlElement{content=Content} = RootEl,
    NewContent=Content++lists:flatten([Data]),
    NewRootEl=RootEl#xmlElement{content=NewContent},    </pre></div>
    <p>Then you can run it through the export_simple/2 function: </p>
    <div class="example"><pre>
    {ok,IOF}=file:open('new_motorcycles.xml',[write]),
    Export=xmerl:export_simple([NewRootEl],xmerl_xml),
    io:format(IOF,"~s~n",[lists:flatten(Export)]),    </pre></div>
    <a name="new_motorcyclesxml"></a>
    <p>The result would be: </p>
<div class="example"><pre>

&lt;?xml version="1.0"?&gt;&lt;motorcycles&gt;
  &lt;bike year="2000" color="black"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Suzuki&lt;/manufacturer&gt;
      &lt;brandName&gt;Suzuki VL 1500&lt;/brandName&gt;
      &lt;additionalName&gt;Intruder&lt;/additionalName&gt;
    &lt;/name&gt;
    &lt;engine&gt;V-engine, 2-cylinders, 1500 cc&lt;/engine&gt;
    &lt;kind&gt;custom&lt;/kind&gt;
    &lt;drive&gt;cardan&lt;/drive&gt;
    &lt;accessories&gt;Sissy bar, luggage carrier,V&amp;amp;H exhaust pipes&lt;/accessories&gt;
  &lt;/bike&gt;
  &lt;date&gt;2004.08.25&lt;/date&gt;
  &lt;bike year="1983" color="read pearl"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Yamaha&lt;/manufacturer&gt;
      &lt;brandName&gt;XJ 400&lt;/brandName&gt;
    &lt;/name&gt;
    &lt;engine&gt;4 cylinder, 400 cc&lt;/engine&gt;
    &lt;kind&gt;alround&lt;/kind&gt;
    &lt;drive&gt;chain&lt;/drive&gt;
    &lt;comment&gt;Good shape!&lt;/comment&gt;
  &lt;/bike&gt;
&lt;bike year="2003" color="black" condition="new"&gt;&lt;name&gt;&lt;manufacturer&gt;Harley Davidsson&lt;/manufacturer&gt;&lt;brandName&gt;XL1200C&lt;/brandName&gt;&lt;additionalName&gt;Sportster&lt;/additionalName&gt;&lt;/name&gt;&lt;engine&gt;V-engine, 2-cylinders, 1200 cc&lt;/engine&gt;&lt;kind&gt;custom&lt;/kind&gt;&lt;drive&gt;belt&lt;/drive&gt;&lt;/bike&gt;&lt;/motorcycles&gt;
</pre></div>    <p>If it is important to get similar indentation and newlines
      as in the original document you have to add #xmlText{} records
      with space and newline values in appropriate places. It may also
      be necessary to keep the original prolog where the DTD is
      referenced. If so, it is possible to pass a RootAttribute
      <span class="code">{prolog,Value}</span> to <span class="code">export_simple/3</span>. The following
      example code fixes those changes in the previous example:</p>
    <div class="example"><pre>
    Data =
      [#xmlText{value="  "},
       {bike,[{year,"2003"},{color,"black"},{condition,"new"}],
             [#xmlText{value="\
    "},
              {name,[#xmlText{value="\
      "},
                     {manufacturer,["Harley Davidsson"]},
                     #xmlText{value="\
      "},
                     {brandName,["XL1200C"]},
                     #xmlText{value="\
      "},
                     {additionalName,["Sportster"]},
                     #xmlText{value="\
    "}]},
              {engine,["V-engine, 2-cylinders, 1200 cc"]},
              #xmlText{value="\
    "},
              {kind,["custom"]},
              #xmlText{value="\
    "},
              {drive,["belt"]},
              #xmlText{value="\
  "}]},
       #xmlText{value="\
"}],
    ...
    NewContent=Content++lists:flatten([Data]),
    NewRootEl=RootEl#xmlElement{content=NewContent},
    ...
    Prolog = ["&lt;?xml version=\\"1.0\\" encoding=\\"utf-8\\" ?&gt;
&lt;!DOCTYPE motorcycles SYSTEM \\"motorcycles.dtd\\"&gt;\
"],
    Export=xmerl:export_simple([NewRootEl],xmerl_xml,[{prolog,Prolog}]),
    ...    </pre></div>
    <p>The result will be: </p>
<div class="example"><pre>

&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;!DOCTYPE motorcycles SYSTEM "motorcycles.dtd"&gt;
&lt;motorcycles&gt;
  &lt;bike year="2000" color="black"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Suzuki&lt;/manufacturer&gt;
      &lt;brandName&gt;Suzuki VL 1500&lt;/brandName&gt;
      &lt;additionalName&gt;Intruder&lt;/additionalName&gt;
    &lt;/name&gt;
    &lt;engine&gt;V-engine, 2-cylinders, 1500 cc&lt;/engine&gt;
    &lt;kind&gt;custom&lt;/kind&gt;
    &lt;drive&gt;cardan&lt;/drive&gt;
    &lt;accessories&gt;Sissy bar, luggage carrier,V&amp;amp;H exhaust pipes&lt;/accessories&gt;
  &lt;/bike&gt;
  &lt;date&gt;2004.08.25&lt;/date&gt;
  &lt;bike year="1983" color="read pearl"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Yamaha&lt;/manufacturer&gt;
      &lt;brandName&gt;XJ 400&lt;/brandName&gt;
    &lt;/name&gt;
    &lt;engine&gt;4 cylinder, 400 cc&lt;/engine&gt;
    &lt;kind&gt;alround&lt;/kind&gt;
    &lt;drive&gt;chain&lt;/drive&gt;
    &lt;comment&gt;Good shape!&lt;/comment&gt;
  &lt;/bike&gt;
  &lt;bike year="2003" color="black" condition="new"&gt;
    &lt;name&gt;
      &lt;manufacturer&gt;Harley Davidsson&lt;/manufacturer&gt;
      &lt;brandName&gt;XL1200C&lt;/brandName&gt;
      &lt;additionalName&gt;Sportster&lt;/additionalName&gt;
    &lt;/name&gt;&lt;engine&gt;V-engine, 2-cylinders, 1200 cc&lt;/engine&gt;
    &lt;kind&gt;custom&lt;/kind&gt;
    &lt;drive&gt;belt&lt;/drive&gt;
  &lt;/bike&gt;
&lt;/motorcycles&gt;
</pre></div>  

  <h3><a name="id60061">1.6 
        Example: Transforming XML To HTML</a></h3>
    
    <p>Assume that you want to transform the <span class="bold_code"><a href="#motorcyclesxml">motorcycles.xml</a></span> document to
      HTML. If you want the same structure and tags of the resulting
      HTML document as of the XML document then you can use the
      <span class="code">xmerl:export/2</span> function. The following:</p>
    <div class="example"><pre>
2&gt; {Doc,Misc}=xmerl_scan:file('motorcycles.xml').
{{xmlElement,motorcycles,
             motorcycles,
             [],
             {xmlNamespace,[],[]},
             [],
             1,
             [],
             [{xmlText,[{motorcycles,1}],1,[],"\
  ",text},
              {xmlElement,bike,
...
3&gt; DocHtml=xmerl:export([Doc],xmerl_html).
["&lt;!DOCTYPE HTML PUBLIC \\"",
 "-//W3C//DTD HTML 4.01 Transitional//EN",
 "\\"",
 [],
 "&gt;\
",
 [[["&lt;","motorcycles","&gt;"],
   ["\
  ",
    [["&lt;",
      "bike",
      [[" ","year","=\\"","2000","\\""],[" ","color","=\\"","black","\\""]],
      "&gt;"],
...    </pre></div>
    <p>Will give the result <span class="bold_code"><a href="result_export.html">result_export.html</a></span></p>
    <p>Perhaps you want to do something more arranged for human
      reading. Suppose that you want to list all different brands in
      the beginning with links to each group of motorcycles. You also
      want all motorcycles sorted by brand, then some flashy colors
      on top of it. Thus you rearrange the order of the elements and
      put in arbitrary HTML tags. This is possible to do by means of
      the <span class="bold_code"><a href="http://www.w3.org/Style/XSL/">XSL Transformation (XSLT)</a></span> like functionality in xmerl. </p>
    <p>Even though the following example shows one way to transform data
      from XML to HTML it also applies to transformations to other
      formats.</p>
    <p><span class="code">xmerl_xs</span> does not implement the entire XSLT
      specification but the basic functionality. For all details see
      the <span class="bold_code"><a href="xmerl_xs.html">reference manual</a></span></p>
    <p>First, some words about the xmerl_xs functionality:</p>
    <p>You need to wright template functions to be able to control
      what kind of output you want. Thus if you want to encapsulate a
      <span class="code">bike</span> element in &lt;p&gt; tags you simply wright a
      function:</p>
    <div class="example"><pre>
template(E = #xmlElement{name='bike'}) -&gt;
    ["&lt;p&gt;",xslapply(fun template/1,E),"&lt;/p&gt;"];    </pre></div>
    <p>With <span class="code">xslapply</span> you tell the XSLT processor in which
      order it should traverse the XML structure. By default it goes
      in preorder traversal, but with the following we make a
      deliberate choice to break that order:</p>
    <div class="example"><pre>
template(E = #xmlElement{name='bike'}) -&gt;
    ["&lt;p&gt;",xslapply(fun template/1,select("bike/name/manufacturer")),"&lt;/p&gt;"];    </pre></div>
    <p>If you want to output the content of an XML element or an attribute you will get the value as a string by the <span class="code">value_of</span> function:</p>
    <div class="example"><pre>
template(E = #xmlElement{name='motorcycles'}) -&gt;
    ["&lt;p&gt;",value_of(select("bike/name/manufacturer",E),"&lt;/p&gt;"];    </pre></div>
    <p>In the xmerl_xs functions you can provide a select(String)
      call, which is an <span class="bold_code"><a href="http://www.w3.org/TR/xpath">XPath</a></span>
      functionality. For more details see the xmerl_xs <span class="bold_code"><a href="xmerl_xs_examples.html">tutorial</a></span>.</p>
    <p>Now, back to the example where we wanted to make the output
      more arranged. With the template:</p>
    <div class="example"><pre>
template(E = #xmlElement{name='motorcycles'}) -&gt;
    [    "&lt;head&gt;\
&lt;title&gt;motorcycles&lt;/title&gt;\
&lt;/head&gt;\
",
         "&lt;body&gt;\
",
\011 "&lt;h1&gt;Used Motorcycles&lt;/h1&gt;\
",
\011 "&lt;ul&gt;\
",
\011 remove_duplicates(value_of(select("bike/name/manufacturer",E))),
\011 "\
&lt;/ul&gt;\
",
\011 sort_by_manufacturer(xslapply(fun template/1, E)),
         "&lt;/body&gt;\
",
\011 "&lt;/html&gt;\
"];    </pre></div>
    <p>We match on the top element and embed the inner parts in an
      HTML body. Then we extract the string values of all motorcycle
      brands, sort them and removes duplicates by
      <span class="code">remove_duplicates(value_of(select("bike/name/manufacturer", E)))</span>. We also process the substructure of the top element
      and pass it to a function that sorts all motorcycle information
      by brand according to the task formulation in the beginning of
      this example.</p>
    <p>The next template matches on the <span class="code">bike</span> element:</p>
    <div class="example"><pre>
template(E = #xmlElement{name='bike'}) -&gt;
    {value_of(select("name/manufacturer",E)),["&lt;dt&gt;",xslapply(fun template/1,select("name",E)),"&lt;/dt&gt;",
    "&lt;dd&gt;&lt;ul&gt;\
",
    "&lt;li style="color:green"&gt;Manufacturing year: ",xslapply(fun template/1,select("@year",E)),"&lt;/li&gt;\
",
    "&lt;li style="color:red"&gt;Color: ",xslapply(fun template/1,select("@color",E)),"&lt;/li&gt;\
",
    "&lt;li style="color:blue"&gt;Shape : ",xslapply(fun template/1,select("@condition",E)),"&lt;/li&gt;\
",
    "&lt;/ul&gt;&lt;/dd&gt;\
"]};    </pre></div>
    <p>This creates a tuple with the brand of the motorcycle and
      the output format. We use the brand name only for sorting
      purpose. We have to end the template function with the "built
      in clause" <span class="code">template(E) -&gt; built_in_rules(fun template/1, E).</span></p>
    <p>The entire program is motorcycles2html.erl:</p>
<div class="example"><pre>

%%%-------------------------------------------------------------------
%%% File    : motorcycles2html.erl
%%% Author  : Bertil Karlsson &lt;bertil@localhost.localdomain&gt;
%%% Description : 
%%%
%%% Created :  2 Sep 2004 by Bertil Karlsson &lt;bertil@localhost.localdomain&gt;
%%%-------------------------------------------------------------------
-module(motorcycles2html).

-include("xmerl.hrl").

-import(xmerl_xs, 
	[ xslapply/2, value_of/1, select/2, built_in_rules/2 ]).

-export([process_xml/1,process_to_file/2,process_to_file/1]).

process_xml(Doc) -&gt;
    template(Doc).

process_to_file(FileName) -&gt;
    process_to_file(FileName,'motorcycles.xml').

process_to_file(FileName,XMLDoc) -&gt;
    case file:open(FileName,[write]) of
	{ok,IOF} -&gt;
	    {XMLContent,_} = xmerl_scan:file(XMLDoc),
	    TransformedXML=process_xml(XMLContent),
	    io:format(IOF,"~s",[TransformedXML]),
	    file:close(IOF);
	{error,Reason} -&gt;
	    io:format("could not open file due to ~p.~n",[Reason])
    end.

%%% templates
template(E = #xmlElement{name='motorcycles'}) -&gt;
    [    "&lt;head&gt;\n&lt;title&gt;motorcycles&lt;/title&gt;\n&lt;/head&gt;\n",
         "&lt;body&gt;\n",
	 "&lt;h1&gt;Used Motorcycles&lt;/h1&gt;\n",
	 "&lt;ul&gt;\n",
	 remove_duplicates(value_of(select("bike/name/manufacturer",E))),
	 "\n&lt;/ul&gt;\n",
	 sort_by_manufacturer(xslapply(fun template/1, E)),
         "&lt;/body&gt;\n",
	 "&lt;/html&gt;\n"];
template(E = #xmlElement{name='bike'}) -&gt;
    {value_of(select("name/manufacturer",E)),["&lt;dt&gt;",xslapply(fun template/1,select("name",E)),"&lt;/dt&gt;",
    "&lt;dd&gt;&lt;ul&gt;\n",
    "&lt;li style=\"color:green\"&gt;Manufacturing year: ",xslapply(fun template/1,select("@year",E)),"&lt;/li&gt;\n",
    "&lt;li style=\"color:red\"&gt;Color: ",xslapply(fun template/1,select("@color",E)),"&lt;/li&gt;\n",
    "&lt;li style=\"color:blue\"&gt;Shape : ",xslapply(fun template/1,select("@condition",E)),"&lt;/li&gt;\n",
    "&lt;/ul&gt;&lt;/dd&gt;\n"]};
template(E) -&gt; built_in_rules(fun template/1, E).


%%%%%%%%%%% helper routines  

%% sorts on the bike name element, unwraps the bike information and
%% inserts a line feed and indentation on each bike element.
sort_by_manufacturer(L) -&gt;
    Tuples=[X1||X1={H,T} &lt;- L],
    SortedTS = lists:keysort(1,Tuples),
    InsertRefName_UnWrap=
	fun([{[Name],V}|Rest],Name,F)-&gt;
		[V|F(Rest,Name,F)];
	   ([{[Name],V}|Rest],PreviousName,F) -&gt;
		[["&lt;a name=\"",Name,"\"&gt;&lt;/&gt;"],V|F(Rest,Name,F)];
	   ([],_,_) -&gt; []
	end,
    SortedRefed=InsertRefName_UnWrap(SortedTS,no_name,InsertRefName_UnWrap),
%    SortedTs=[Y||{X,Y}&lt;-lists:keysort(1,Tuples)],
    WS = "\n    ",
    Fun=fun([H|T],Acc,F)-&gt;
		F(T,[H,WS|Acc],F);
	   ([],Acc,F)-&gt;
		lists:reverse([WS|Acc])
	end,
    if length(SortedRefed) &gt; 0 -&gt;
	    Fun(SortedRefed,[],Fun);
       true -&gt; []
    end.

    
%% removes all but the first of an element in L and inserts a html
%% reference for each list element.
remove_duplicates(L) -&gt;
    remove_duplicates(L,[]).

remove_duplicates([],Acc) -&gt; 
    make_ref(lists:sort(lists:reverse(Acc)));
remove_duplicates([A|L],Acc) -&gt; 
    case lists:delete(A,L) of
	L -&gt;
	    remove_duplicates(L,[A|Acc]);
	L1 -&gt; 
	    remove_duplicates([A|L1],[Acc])
    end.

make_ref([]) -&gt; [];
make_ref([H]) when atom(H) -&gt;
    "&lt;ul&gt;&lt;a href=\"#"++atom_to_list(H)++"\"&gt;"++atom_to_list(H)++"&lt;/a&gt;&lt;/ul&gt;";
make_ref([H]) when list(H) -&gt;
    "&lt;ul&gt;&lt;a href=\"#"++H++"\"&gt;\s"++H++"&lt;/a&gt;&lt;/ul&gt;";
make_ref([H|T]) when atom(H) -&gt;
    ["&lt;ul&gt;&lt;a href=\"#"++atom_to_list(H)++"\"&gt;\s"++atom_to_list(H)++",\n&lt;/a&gt;&lt;/ul&gt;"
     |make_ref(T)];
make_ref([H|T]) when list(H) -&gt;
    ["&lt;ul&gt;&lt;a href=\"#"++H++"\"&gt;\s"++H++",\n&lt;/a&gt;&lt;/ul&gt;"|make_ref(T)].

</pre></div>    <p>If we run it like this:
      <span class="code">motorcycles2html:process_to_file('result_xs.html', 'motorcycles2.xml').</span> The result will be <span class="bold_code"><a href="result_xs.html">result_xs.html</a></span>. When the
      input file is of the same structure as the previous
      "motorcycles" XML files but it has a little more 'bike'
      elements and the 'manufacturer' elements are not in order.</p>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 2004-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>