<!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> <?xml version="1.0"?> <dog> Grand Danois </dog> </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> <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE motorcycles SYSTEM "motorcycles.dtd"> <motorcycles> <bike year="2000" color="black"> <name> <manufacturer>Suzuki</manufacturer> <brandName>Suzuki VL 1500</brandName> <additionalName>Intruder</additionalName> </name> <engine>V-engine, 2-cylinders, 1500 cc</engine> <kind>custom</kind> <drive>cardan</drive> <accessories>Sissy bar, luggage carrier,V&amp;H exhaust pipes</accessories> </bike> <date>2004.08.25</date> <bike year="1983" color="read pearl"> <name> <manufacturer>Yamaha</manufacturer> <brandName>XJ 400</brandName> </name> <engine>4 cylinder, 400 cc</engine> <kind>alround</kind> <drive>chain</drive> <comment>Good shape!</comment> </bike> </motorcycles> </pre></div> <p>and motorcycles.dtd looks like: </p> <div class="example"><pre> <?xml version="1.0" encoding="utf-8" ?> <!ELEMENT motorcycles (bike,date?)+ > <!ELEMENT bike (name,engine,kind,drive, accessories?,comment?) > <!ELEMENT name (manufacturer,brandName,additionalName?) > <!ELEMENT manufacturer (#PCDATA)> <!ELEMENT brandName (#PCDATA)> <!ELEMENT additionalName (#PCDATA)> <!ELEMENT engine (#PCDATA)> <!ELEMENT kind (#PCDATA)> <!ELEMENT drive (#PCDATA)> <!ELEMENT comment (#PCDATA)> <!ELEMENT accessories (#PCDATA)> <!-- Date of the format yyyy.mm.dd --> <!ELEMENT date (#PCDATA)> <!ATTLIST bike year NMTOKEN #REQUIRED color NMTOKENS #REQUIRED condition (useless | bad | serviceable | moderate | good | excellent | new | outstanding) "excellent" > </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> {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> </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">"<"</span> or a <span class="code">"&"</span> character it must be written as <span class="code">"&lt;"</span> and <span class="code">"&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> <?xml version="1.0"?><motorcycles> <bike year="2000" color="black"> <name> <manufacturer>Suzuki</manufacturer> <brandName>Suzuki VL 1500</brandName> <additionalName>Intruder</additionalName> </name> <engine>V-engine, 2-cylinders, 1500 cc</engine> <kind>custom</kind> <drive>cardan</drive> <accessories>Sissy bar, luggage carrier,V&amp;H exhaust pipes</accessories> </bike> <date>2004.08.25</date> <bike year="1983" color="read pearl"> <name> <manufacturer>Yamaha</manufacturer> <brandName>XJ 400</brandName> </name> <engine>4 cylinder, 400 cc</engine> <kind>alround</kind> <drive>chain</drive> <comment>Good shape!</comment> </bike> <bike year="2003" color="black" condition="new"><name><manufacturer>Harley Davidsson</manufacturer><brandName>XL1200C</brandName><additionalName>Sportster</additionalName></name><engine>V-engine, 2-cylinders, 1200 cc</engine><kind>custom</kind><drive>belt</drive></bike></motorcycles> </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 = ["<?xml version=\\"1.0\\" encoding=\\"utf-8\\" ?> <!DOCTYPE motorcycles SYSTEM \\"motorcycles.dtd\\">\ "], Export=xmerl:export_simple([NewRootEl],xmerl_xml,[{prolog,Prolog}]), ... </pre></div> <p>The result will be: </p> <div class="example"><pre> <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE motorcycles SYSTEM "motorcycles.dtd"> <motorcycles> <bike year="2000" color="black"> <name> <manufacturer>Suzuki</manufacturer> <brandName>Suzuki VL 1500</brandName> <additionalName>Intruder</additionalName> </name> <engine>V-engine, 2-cylinders, 1500 cc</engine> <kind>custom</kind> <drive>cardan</drive> <accessories>Sissy bar, luggage carrier,V&amp;H exhaust pipes</accessories> </bike> <date>2004.08.25</date> <bike year="1983" color="read pearl"> <name> <manufacturer>Yamaha</manufacturer> <brandName>XJ 400</brandName> </name> <engine>4 cylinder, 400 cc</engine> <kind>alround</kind> <drive>chain</drive> <comment>Good shape!</comment> </bike> <bike year="2003" color="black" condition="new"> <name> <manufacturer>Harley Davidsson</manufacturer> <brandName>XL1200C</brandName> <additionalName>Sportster</additionalName> </name><engine>V-engine, 2-cylinders, 1200 cc</engine> <kind>custom</kind> <drive>belt</drive> </bike> </motorcycles> </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> {Doc,Misc}=xmerl_scan:file('motorcycles.xml'). {{xmlElement,motorcycles, motorcycles, [], {xmlNamespace,[],[]}, [], 1, [], [{xmlText,[{motorcycles,1}],1,[],"\ ",text}, {xmlElement,bike, ... 3> DocHtml=xmerl:export([Doc],xmerl_html). ["<!DOCTYPE HTML PUBLIC \\"", "-//W3C//DTD HTML 4.01 Transitional//EN", "\\"", [], ">\ ", [[["<","motorcycles",">"], ["\ ", [["<", "bike", [[" ","year","=\\"","2000","\\""],[" ","color","=\\"","black","\\""]], ">"], ... </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 <p> tags you simply wright a function:</p> <div class="example"><pre> template(E = #xmlElement{name='bike'}) -> ["<p>",xslapply(fun template/1,E),"</p>"]; </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'}) -> ["<p>",xslapply(fun template/1,select("bike/name/manufacturer")),"</p>"]; </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'}) -> ["<p>",value_of(select("bike/name/manufacturer",E),"</p>"]; </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'}) -> [ "<head>\ <title>motorcycles</title>\ </head>\ ", "<body>\ ", \011 "<h1>Used Motorcycles</h1>\ ", \011 "<ul>\ ", \011 remove_duplicates(value_of(select("bike/name/manufacturer",E))), \011 "\ </ul>\ ", \011 sort_by_manufacturer(xslapply(fun template/1, E)), "</body>\ ", \011 "</html>\ "]; </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'}) -> {value_of(select("name/manufacturer",E)),["<dt>",xslapply(fun template/1,select("name",E)),"</dt>", "<dd><ul>\ ", "<li style="color:green">Manufacturing year: ",xslapply(fun template/1,select("@year",E)),"</li>\ ", "<li style="color:red">Color: ",xslapply(fun template/1,select("@color",E)),"</li>\ ", "<li style="color:blue">Shape : ",xslapply(fun template/1,select("@condition",E)),"</li>\ ", "</ul></dd>\ "]}; </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) -> 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 <bertil@localhost.localdomain> %%% Description : %%% %%% Created : 2 Sep 2004 by Bertil Karlsson <bertil@localhost.localdomain> %%%------------------------------------------------------------------- -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) -> template(Doc). process_to_file(FileName) -> process_to_file(FileName,'motorcycles.xml'). process_to_file(FileName,XMLDoc) -> case file:open(FileName,[write]) of {ok,IOF} -> {XMLContent,_} = xmerl_scan:file(XMLDoc), TransformedXML=process_xml(XMLContent), io:format(IOF,"~s",[TransformedXML]), file:close(IOF); {error,Reason} -> io:format("could not open file due to ~p.~n",[Reason]) end. %%% templates template(E = #xmlElement{name='motorcycles'}) -> [ "<head>\n<title>motorcycles</title>\n</head>\n", "<body>\n", "<h1>Used Motorcycles</h1>\n", "<ul>\n", remove_duplicates(value_of(select("bike/name/manufacturer",E))), "\n</ul>\n", sort_by_manufacturer(xslapply(fun template/1, E)), "</body>\n", "</html>\n"]; template(E = #xmlElement{name='bike'}) -> {value_of(select("name/manufacturer",E)),["<dt>",xslapply(fun template/1,select("name",E)),"</dt>", "<dd><ul>\n", "<li style=\"color:green\">Manufacturing year: ",xslapply(fun template/1,select("@year",E)),"</li>\n", "<li style=\"color:red\">Color: ",xslapply(fun template/1,select("@color",E)),"</li>\n", "<li style=\"color:blue\">Shape : ",xslapply(fun template/1,select("@condition",E)),"</li>\n", "</ul></dd>\n"]}; template(E) -> 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) -> Tuples=[X1||X1={H,T} <- L], SortedTS = lists:keysort(1,Tuples), InsertRefName_UnWrap= fun([{[Name],V}|Rest],Name,F)-> [V|F(Rest,Name,F)]; ([{[Name],V}|Rest],PreviousName,F) -> [["<a name=\"",Name,"\"></>"],V|F(Rest,Name,F)]; ([],_,_) -> [] end, SortedRefed=InsertRefName_UnWrap(SortedTS,no_name,InsertRefName_UnWrap), % SortedTs=[Y||{X,Y}<-lists:keysort(1,Tuples)], WS = "\n ", Fun=fun([H|T],Acc,F)-> F(T,[H,WS|Acc],F); ([],Acc,F)-> lists:reverse([WS|Acc]) end, if length(SortedRefed) > 0 -> Fun(SortedRefed,[],Fun); true -> [] end. %% removes all but the first of an element in L and inserts a html %% reference for each list element. remove_duplicates(L) -> remove_duplicates(L,[]). remove_duplicates([],Acc) -> make_ref(lists:sort(lists:reverse(Acc))); remove_duplicates([A|L],Acc) -> case lists:delete(A,L) of L -> remove_duplicates(L,[A|Acc]); L1 -> remove_duplicates([A|L1],[Acc]) end. make_ref([]) -> []; make_ref([H]) when atom(H) -> "<ul><a href=\"#"++atom_to_list(H)++"\">"++atom_to_list(H)++"</a></ul>"; make_ref([H]) when list(H) -> "<ul><a href=\"#"++H++"\">\s"++H++"</a></ul>"; make_ref([H|T]) when atom(H) -> ["<ul><a href=\"#"++atom_to_list(H)++"\">\s"++atom_to_list(H)++",\n</a></ul>" |make_ref(T)]; make_ref([H|T]) when list(H) -> ["<ul><a href=\"#"++H++"\">\s"++H++",\n</a></ul>"|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>