<?xml version="1.0"?>
<!DOCTYPE HTML SYSTEM  "/home/duncan/Projects/S4/library/documentation/dtd/html32.dtd">
<html> <head>
<title>R &amp; SPlus XML Parsers</title>
<link rel="stylesheet" href="../../../Docs/OmegaTech.css" />
</head>

<body>

<h1>R &amp; SPlus XML Parsers</h1>
Latest version: <a href="@TAR_FILE@">@TAR_FILE@</a>
<p align="right"><a href="@TAR_FILE@">R Package</a></p>
<p />
<ul>
  <li> <a href="#Overview">Overview</a></li>
  <li> <a href="#PackageOverview">Package Overview</a> </li>
  <li> <a href="#Examples">Examples</a></li>
      <ul>
	<li><a href="#TreeExamples">Tree-based.</a> </li>
	<li><a href="#EventExamples">Event-driven</a>.</li>
      </ul>
  <li> <a href="WritingXML.html#ReadingDTDs">Reading DTDs</a> </li>      
  <li> <a href="#PackageInfo">Obtaining the software</a></li>
      <ul>
	<li> <a href="#Unix">Unix</a>
	<li> <a href="#Windows">Windows</a>	    
      </ul>
  <li> <a href="#License">License</a></li>
  <li> <a href="#Installation">Installation</a></li>
      <ul>
	<li> <a href="#InstallPackage">Installing from</a> <a href="@TAR_FILE@">@TAR_FILE@</a></li>
      </ul>
  <li> <a href="#FileList">FileList</a></li>
  <li> <a href="#OtherInstalls">Installing libxml and/or Expat</a></li>
      <ul>
	<li> <a href="#Expat">Exapt</a></li>
	<li> <a href="#libml">libxml</a>	</li>    
      </ul>
  <li> <a href="#Features">Features</a></li>
  <li> <a href="Changes"><img src="../../../Images/new.gif"></img>Recent Changes</a>
  <li> <a href="Todo.html">List of Things To Add, Fix, etc.</a>      </li>
</ul>


<h1><img src="../../../Images/new.gif"></img>Latest News</h1>
<dl>
  <dt>
  <li> <font color="red">Support for S4/Splus5 for the Tree
      Parsing</font></li>
      </dt>
  <dd> Event driven parsing and function callbacks not yet added for
      S4/Splus5. Requires mutable state and hence integration of the
      CORBA/Java/XML driver interface for this kind of thing.</dd>

  <dt>
  <li> Fix of some trivial bugs.</li></dt>
  <dd></dd>
</dl>


<h2><a name="Overview">Overview</a></h2>

XML is one of several facilities we are investigating for enhancing
communication between applications.  The ability to easily transfer
data between applications is enhanced if the data is
<i>self-describing</i>.  One can imagine datasets being well-formed
documents that specify a DTD specifying their format.  For example, <a
href="http://lib.stat.cmu.edu">Statlib</a> datasets would contain
information about the variables, number of observations, levels of
factors, etc.  as well as meta-data about the source of the data,
precision, additional commands for specific systems to assist in
interpreting the data.  This format allows readers to perform single
passes by announcing their dimensions, types, etc. at the top of the
document. Additionally, entities in the DTD and document can contain
code for specific systems. These then act as "portable" methods.
(Security is an issue, but somewhat orthogonal to the parsing mechanism.)

<p/>

Data can also be exchanged dynamically with other systems that use
XML.  For example, Office, Oracle, Lotus Notes, browsers, HTTP
servers, etc.

<p/>

The markup language for mathematics -  <a
href="http://www.w3.org/Math/">MathML</a>  - will be  important
in the research end of statistics, and also to some extend the applied
data analysis for specifying models, etc.
See <a href="MathMLExample">Math ML Example</a>
and you can fetch the DTD from
<a href="http://www.w3.org/1999/07/REC-MathML-19990707/mmlents.zip">mmlents.zip</a>


<p/>

<a href="http://www.w3.org/Graphics/SVG/">Scalable Vector Graphics</a>
is an XML based format for specifying graphics descriptions that
can be scaled easily without distortion. We may be using it (or an
extension of it) in Omegahat to represent plots.
The DTD is available from <a href="http://www.w3.org/TR/1999/WD-SVG-19991203/svgdtd.html">here</a>.


<p/>

Since XML is similar to HTML, we can encourage people to use this type
of format for different inputs. We have effectively used for defining
options with potentially more complicated structures than simple
name-value pairs. Hierarchical structures are easily handled by XML.
Plot descriptions can be described in this way, and indeed we intend
to do this in Omegahat.

<p/>

This XML-approach is in contrast to a simple ASCII or native object dump which relies
on the receiving system or user to understand the format.
(Communicating via the S4 object ASCII dump format was used
effectively to communicate between Java and S4, but was heavily
dependent on the parsing facilities being migrated to Java, and any
other system engaging in such communication.)
<br/>
In contrast
with the <a href="http://www.omegahat.net/Interfaces/Java">embedded
Java facilities</a> and <a
href="http://www.omegahat.net/Interfaces/Java">CORBA</a> packages for
R and S, XML is a more static representation of data rather than a
live object offering methods.

<p/>

In addition to providing an environment neutral form of persistence,
XML can be used for configuration files, plot template descriptions,
documentation, etc.

<p/>

The aim of providing facilities in R and S for reading XML at the user
level is to encourage users to consider the development of DTDs for
statistical data and concepts. If we can "standardize" on some basic
descriptions, we can exchange data easily between numerous systems,
including spreadsheets, etc.  These DTDs, coupled with Java
<i>interface</i> classes and IDL modules create an integrated
framework for open network computing in multiple ways and at multiple
user levels.  We strongly encourage people to actively make their DTDs
available to others.

<p/>

In the future, we will develop facilities for writing objects from R,
S and Omegahat in XML format using the DTDs we develop. A general
mechanism for having validated output filters can be created.
See <a href="WritingXML.html">Writing XML</a>

<h2><a name="PackageOverview">Package Overview</a></h2>

This is a small, but sufficient, collection of both C routines and R
and S functions for reading the contents of XML files for processing
in these two environments. There are two general styles of XML
parsers.

<dl>
  <dt> 
  <li>Document/Tree-based.</li></dt>
  <dd> Here, the entire XML document is read and a tree constructed containing the
different elements in the document. At this point, we process the
elements by traversing the tree and generating a user-level
representation of the nodes. We allow the user to specify functions
that are called for different types of nodes so that she can customize
the resulting tree as it is being constructed.
  </dd>
  <dt>
  <li> Event driven.</li></dt>
  <dd> This style involves reading the XML elements in the document
one at a time and invoking different user level functions/methods that
correspond to the type of element - a tag, text, entity, CData,
etc. The methods are responsible for processing the information
locally and building the appropriate data structure from all of
them. Thus, no tree need be constructed and traversed
post-construction. This reduces the memory used in reading the
document and provides much greater control over the parsing.
</dd>
</dl>
<p />

Rather than offering one of these styles, we provide functions that
work both ways for R. In S, we currently only support the
document/tree-based approach.  <code>xmlTreeParse()</code> is the tree
based version which generates an internal tree and then converts it to
a list of lists in R/S. This is uses the <a
href="http://xmlsoft.org/">XML library</a> from Daniel
Veillard of W3.org.

<p/>

The second function, <code>xmlEventParse()</code>, is event driven.  The user
specifies a collection of R/S-level functions, in addition to the file
name, and the parser invokes the appropriate function as new XML elements
are encountered.  The C-level parser we use is Expat developed by
<a href="http://www.jclark.com">Jim Clark</a>. 

<p/>

Unless you have very large XML documents, if you want to experiment
with just one parser, use the first of these, i.e the document-based
one.  That is the simplest to use, sacrificing control of the creation
of the data structures and potential memory growth.

<p/>


In R, the collection of functions is usually a closure and it can
manipulate local data. In S, these are usually
a list of functions. In order to handle mutable state, one should
use  the <a href="http://cm.bell-labs.com/stat/jmc/">interface
driver</a> mechanism. 
 The closure approach is described in more detail in
<code>Docs/Outline.nw</code> and the R document in <code
class="dir">man/</code>.


<h2><a name="Examples">Examples</a></h2>
<h3><a name="TreeExamples">Tree-Based Parsing</a></h3>

The first thing we do is perform a simple parse of a document.
Make certain to specify the correct location of the file.
<pre>
>  x &lt;-  xmlTreeParse("data/test.xml")
> names(x)
[1] "file"     "version"  "children"
> x$file
[1] "data/test.xml"
> names(x$children[[1]])
[1] "name"       "attributes" "children"   "value"     
>
</pre>
<p/>

Now we turn our attention to manipulating the previously generated
tree. We can do this in R/S using the following version of
<code>treeApply</code>.
<pre>
treeApply &lt;- function(x, func, post=NULL, pre=NULL, ...) {
 ans &lt;- NULL

 value &lt;- func(x)

 if(length(value))
   ans &lt;- list(value=value)

   # If there are any children, do a recursive apply on those also.
   # If the result is non-null
 if( length(x[["children"]]) > 0 ) {
   tmp &lt;- lapply(x[["children"]], treeApply, func, ...)
   if(length(tmp) > 0)
     ans$children - tmp
 }

  # invoke the post-processing of children hook.
 if(length(post)) {
   post(x)
 }

 invisible(ans)
}
</pre>

Armed with this version of <code>apply()</code>, we can start doing
some processing of the tree. First, lets display the type of each node in the tree.
<pre>
v &lt;- treeApply(x, function(x) cat(class(x),"\n"))
named 
XMLComment 
XMLNode 
XMLNode 
XMLNode 
XMLEntityRef 
XMLProccesingInstruction 
XMLNode 
XMLNode 
XMLNode 
</pre>

A slightly more interesting example is to
produce a graphical display of the tree.
I use <a href="http://www.tug.org/applications/PSTricks/">PStricks</a>
for this purpose.
We define a node function that produces the relevant TeX commands
and also a <code>post</code> function to tidy up the groups.
<pre>
foo &lt;-  function(x) {
     label &lt;- ifelse(length(x$value), x$value, ifelse(length(x$name), x$name,"doc"))
     if(length(x[["children"]])==0) {
                                 cat("\\Tr{",label,"}%\n",sep="")
      } else {
         cat("\\pstree{\\Tr{",label,"}}{%\n",sep="")
      }
}

 post &lt;- function(x) if(length(x$children) > 0) cat("}\n")
treeApply(x, foo, post= post)
</pre>
The result is
<pre>
\pstree{\Tr{doc}}{%
\Tr{ A comment }%
\pstree{\Tr{foo}}{%
\Tr{element}%
\Tr{ }%
\Tr{test entity}%
\Tr{print "This is some more PHP code being executed."; }%
\pstree{\Tr{duncan}}{%
\pstree{\Tr{temple}}{%
\Tr{extEnt;}%
}
}
}
}
</pre>


<p/>

Note that the post function is more naturally done
in an event-driven parser, via the
<code>endElement</code> handler.


<p/>


<p/>
Another example is that this document has been carefully constructed
to be parseable by the <code>xmlTreeParse</code>
function.
<pre>
 v &lt;- xmlTreeParse("index.html")
</pre>



<h3><a name="EventExamples">Event-driven Examples</a></h3>

The event-driven style is essentially a filtering mechanism.  It
provides lower level control over the processing of the
elements. Because both R and S do not have references, incremental
processing is slightly more complicated than it is in languages such
as C or Java.  However, the event-driven style does allow us to avoid
reading the entire document into memory at once and is ideal for
situations when most of the document is not of interest, but a small
number of nodes are important and their location in the document is
necessary to understand.

<p/>

A simple example is where we gather all the character text in the
document.  In other words, we throw away the XML hierarchical
structure and any nodes that are not simply character text.


<pre>
characterOnlyHandler &lt;- function() {
  txt &lt;- NULL
  text &lt;- function(val,...) {
    txt &lt;&lt;- c(txt, val)
  }

  getText &lt;- function() { txt }

  return(list(text=text, getText=getText))
}

z &lt;- xmlEventParse("data/job.xml", characterOnlyHandler())
z$getText()
 [1] "  "                                                                   
 [2] "    "                                                                 
 [3] "      "                                                               
 [4] "      "                                                               
 [5] "GBackup"                                                              
 [6] "      "                                                               
 [7] "Development"                                                          
 [8] "      "                                                               
 [9] "        "                                                             
[10] "Open"                                                                 
[11] "        "                                                             
[12] "Mon, 07 Jun 1999 20:27:45 -0400 MET DST"                              
[13] "        "                                                             
[14] "USD 0.00"                                                             
[15] "      "                                                               
[16] "      "                                                               
[17] "        "                                                             
[18] "        "                                                             
[19] "      "                                                               
[20] "      "                                                               
[21] "        "                                                             
[22] "Nathan Clemons"                                                       
[23] "        "                                                             
[24] "nathan@windsofstorm.net"                                              
[25] "        "                                                             
[26] "        "                                                             
[27] "        "                                                             
[28] "        "                                                             
[29] "        "                                                             
[30] "        "                                                             
[31] "        "                                                             
[32] "        "                                                             
[33] "        "                                                             
[34] "        "                                                             
[35] "      "                                                               
[36] "      "                                                               
[37] "      The program should be released as free software, under the GPL."
[38] "      "                                                               
[39] "    "                                                                 
[40] "  "                                                                   
</pre>

Note that we can discard the lines that are simply white space
using the <code>trim</code> argument.
This trims all text values. More granularity is needed here.
<pre>
z &lt;- xmlEventParse("data/job.xml", characterOnlyHandler(), ignoreBlanks=T, trim=T)
&gt; z$getText()
[1] "GBackup"                                                        
[2] "Development"                                                    
[3] "Open"                                                           
[4] "Mon, 07 Jun 1999 20:27:45 -0400 MET DST"                        
[5] "USD 0.00"                                                       
[6] "Nathan Clemons"                                                 
[7] "nathan@windsofstorm.net"                                        
[8] "The program should be released as free software, under the GPL."
</pre>

<p/>
Much as we did with the tree-based parser,
we can construct a display of the structure of the document
using the event driven parser.
<pre>
 xmlEventParse("data/job.xml",
                 list(startElement = function(x,...){
                                      cat("\\pstree{\\Tr{",x[[1]],"}}{%\n",sep="")
                                     },
                      endElement   = function(x,...)
                                            cat("}\n")
                     ))
</pre>

Note that we use a list of functions rather than a closure in this
example.  This is because we do not have data that persists across
function calls.


<p/>

Parsing the <code class="file">mtcars.xml</code> file (or generally
files using the DTD used by that file) can be done via the event
parser in the following manner.  First we define a closure with
methods for handling the different tags of interest.  Rather than
using startElement and looking at the name of the tag/element, we will
instruct the <code>xmlEventParse</code> to look for a method whose
name is the same as the tag, before defaulting to use the
<code>startElement()</code> method.  As with most event driven
material, the logic is different and may seem complicated.  The idea
is that we will see the <code>dataset</code> tag first. So we define a
function with this name. The <code>dataset</code> tag will have
attributes that we store to attach to the data frame that we construct
from reading the entire XML structure.  Of special interest in this
list is the number of records.  We store this separately, converting
it to an integer, so that when we find the number of variables, we can
allocate the array.

<p/>


The next we do is define a method for handling the
<code>variables</code> element. There we find the number of variables.
Note that if the DTD didn't provide this count, we could defer the
computation of variables and the allocation of the array until we saw
the end of the <code>variables</code> tag.  This would allow the user
to avoid having to specify the number of variables explicitly.

<p/>

As we encounter each <code>variable</code> element, we expect the next
<code>text</code> element to be the name of the variable.  So, within
the <code class="SFunction">variable()</code> method, we set the flag
<code>expectingVariableName</code> to be true.  Then in the <code
class="SFunction">text()</code> function, we interpret the value as
either a variable name if <code>expectingVariableName</code> is true,
or as the value of a record if not.  In the former case, we append the
value to the list of variable names in <code>varNames</code>.  We need
to set the value <code>expectingVariableName</code> to false when we
have enough. We do this when the length of <code>varNames</code>
equals the number of columns in <code>data</code>, computed from the
<code class="xmlAttribute">count</code> attribute.

<p/>

A different way to do this is to have an <code>endElement()</code>
function which set <code>expectingVariableName</code> to false when
the element being ended was <code>variables</code>.  Again, this is a
choice and different implementations will have advantages with respect
to robustness, error handling, etc.

<p/>

The <code>text()</code> function handles the case where we are not
expecting the name of a variable, but instead interpret the string as
the value of a record.  To do this, we have to convert the collection
of numbers separeted by white space to a numeric vector.  We do this
by splitting the string by white space and the converting each entry
to a numeric value.  We assign the resulting numeric vector to the
matrix <code>data</code> in the current row.  The index of the record
is stored in <code>currentRecord</code>.  This is incremented by the
<code>record</code> method. (We could do this in <code>text()</code>
also, but this is more interesting.)

<p/>
We will ignore issues where the values are separated across
lines, contain strings, etc. The latter is orthogonal  to the event
driven XML parsing. The former (partial record per line) can be
handled by computing the number seen so far for this record and
storing this across calls to <code>text()</code> and adding to the 
appropriate columns.

<pre>
 handler &lt;- function() {
  data &lt;- NULL

    # Private or local variables used to store information across 
    # method calls from the event parser
  numRecords &lt;- 0
  varNames &lt;- NULL
  meta &lt;- NULL
  currentRecord &lt;- 0
  expectingVariableName &lt;- F
  rowNames &lt;- NULL

   # read the attributes from the dataset
  dataset &lt;- function(x,atts) {
    numRecords &lt;&lt;- as.integer(atts[["numRecords"]])
      # store these so that we can put these as attributes
      # on data when we create it.
    meta &lt;&lt;- atts
  }

  variables &lt;- function(x, atts) {
      # From the DTD, we expect a count attribute telling us the number
      # of variables.
    data &lt;&lt;- matrix(0., numRecords, as.integer(atts[["count"]]))
      #  set the XML attributes from the dataset element as R
      #  attributes of the data.
    attributes(data) &lt;&lt;- c(attributes(data),meta)
  }

  # when we see the start of a variable tag, then we are expecting
  # its name next, so handle text accordingly.
  variable &lt;- function(x,...) {
     expectingVariableName &lt;&lt;- T
  }

  record &lt;- function(x,atts) {
      # advance the current record index.
    currentRecord &lt;&lt;- currentRecord + 1
    rowNames &lt;&lt;- c(rowNames, atts[["id"]])
  }

  text &lt;- function(x,...) {
   if(x == "")
     return(NULL)

   if(expectingVariableName) {
     varNames &lt;&lt;- c(varNames, x)  
     if(length(varNames) &gt;= ncol(data)) {
         expectingVariableName &lt;&lt;- F
         dimnames(data) &lt;&lt;- list(NULL, varNames)
     }
   } else {
      e &lt;- gsub("[ \t]*",",",x)
      vals &lt;- sapply(strsplit(e,",")[[1]], as.numeric)
      data[currentRecord,] &lt;&lt;- vals
   }
  }

    # Called at the end of each tag.
  endElement &lt;- function(x,...) {
   if(x == "dataset") {
         # set the row names for the matrix.
       dimnames(data)[[1]]  &lt;&lt;- rowNames
    }
  }

   return(list(variable = variable,
               variables = variables,
               dataset=dataset,
               text  = text,
               record= record,
               endElement = endElement,
               data = function() {data },
               rowNames = function() rowNames
              ))
}
</pre>

A more robust version of this that handles rownames and produces a
data frame rather than a is given in the function <a
href="data/dataFrame.html">dataFrameEvents</a>



<h2><a name="PackageInfo">Obtaining the Software</a></h2>

<h3><a name="Unix">Unix</a></h3>
The package is maintained as part of the <a
href="http://www.omegahat.net/download/index.html">Omegahat source
tree</a>, under the control of the <a
href="http://www.omegahat.net">Omega Project for Statistical
computing</a>.  You can obtain the source in the following ways:

<dl>
  <dt>
  <li> <a
      href="http://www.omegahat.net/RSXML/@TAR_FILE@">R package</a></li></dt>
  <dd> The uncompiled, installable version as an R package.
       This is probably the easiest to install as
       at the end you can simply invoke <code>library(XML)</code>.
       <br />
        You can use the GNUmakefiles in libxml and expat
        to configure each of those distributions appropriately.
        (Basically, these build shared libraries.)
</dd>
  <dt>
  <li> <a  href="http://www.omegahat.net/download/R/xml/xml.tar.gz">Basic source</a></li></dt>

  <dd> (What is this?)<br>
       The raw source. This compiles the same way as the R package.
       It just cannot be loaded as easily.
   </dd>
  <dt>
  <li> <a href="http://www.omegahat.net/cvsweb">via anonymous CVS</a></li></dt>
  <dd> The most up-to-date raw source.
   </dd>   
</dl>

There are no binaries for Unix.
If there is a need, please ask.

<p />
This software is known to run on both Linux (RedHat 6.1) and Solaris
(2.6). 

<p />
To run the R functions, you will need to install
either or both of the following packages.
<ul>
  <li> <a
      href="http://rpmfind.net/veillard/XML/">libxml</a>
       for the document/tree based parsing.
</li>            
  <li> <a href="ftp://ftp.jclark.com/pub/xml/expat.zip">expat</a>
       for the event based parsing.
</li>      
</ul>
See <a href="#OtherInstalls">Installing 3rd party software</a>.


<h2><a name="License">License</a></h2>

The code, documentation, etc. is released under the terms of the GNU
General Public License and the owner of the copyright is the Omega
Project for Statistical Computing.

<p/>

The goal is to share this code with an S4/Splus5 version.  In order to
keep the programming interfaces consistent, we would appreciate being
notified of changes.


<h2><a name="Installation">Installation</a></h2>

The package, also known as chapter, can be configured to use either of
the XML parsing styles discussed in the <a
href="#PackageOverview">above</a>, <b>or both</b>.  The event-based parser
uses the <a href="http://www.jclark.com/xml">Expat library</a> by <a
href="http://www.jclark.com">Jim Clark </a>.  The tree/document-based
parser uses <a
href="http://rpmfind.net/veillard/XML/">libxml</a> from
Daniel Veillard.  You can use either or both of these. First install
whichever of these you will use, and make sure to build them as shared
libraries.  See below for some assistance in doing this.

<p />

Having decided to use either libxml and/or expat, you must specify
their locations.  Edit the <code>GNUmakefile</code>, and uncomment the
line defining <code>LIBXML</code> and/or <code>LIBEXPAT</code> as
appropriate. Change the value on the right hand side of the = sign to
the location of these directories.

<p/>

Next, you need to specify whether you are building for R or S4/Splus5.
You can do this via the variable <code>LANGUAGE</code> in the
<code>GNUmakefile</code>.
It defaults to R.

All of these can be specified on the command line such as:
<pre>
  make LIBXML=$HOME/libxml-1.7.3 LIBEXPAT=$HOME/expat LANGUAGE=R CC=gcc
</pre>


<h3><a name="InstallPackage">Installing from @TAR_FILE@</a></h3>

<ol>
  <li> Untar the @TAR_FILE@ file in the appropriate directory,
       probably one of the library/ directories your R distribution
       searches for libraries. (See library(), R_LIBS, etc.)
</li>      
  <li> <code>cd XML</code>
</li>            
  <li> Invoke make, specifying the different values for the
       3rd party distributions, etc. on the command line.
</li>      
<pre>
       make LIBXML=$HOME/libxml-1.7.3 LIBEXPAT=$HOME/expat LANGUAGE=R CC=gcc
</pre>      
</ol>



<p />

I have installed using the makefiles here and the
<code class="file">GNUmakefile.admin</code> in the omegahat source tree version of this. That
however relies on some other makefiles in the R section of the
Omegahat tree.  If any one else wishes to package this, please send me
the changes I can make them available to others.  Of course you can
use it by just attaching the chapter and using <code>dyn.load()</code>.

<br/>

Some of this would be easier if we used either the R or S4/Splus5
package installation facilities.  However, I do not have time at the
moment to handle both cases in the common code.

<p />

Make sure to specify the location of the library path. Use the
environment variable <code>LD_LIBRARY_PATH</code> to include the
location of the libxml distribution and also the lib directory in the
expat distribution.
<pre>
  setenv LD_LIBRARY_PATH ${LIBXML}:${LIBEXPAT}/lib
</pre>
or, in bash
<pre>
  export LD_LIBRARY_PATH=${LIBXML}:${LIBEXPAT}/lib
</pre>


<h3><a name="Windows">Microsoft Windows</a></h3>

There is now a version of the package for Windows.
One can install from <a href="@TAR_FILE@">source</a> or download a <a
href="http://www.stats.ox.ac.uk/pub/RWin/">binary, pre-compiled version</a> of the package
from Brian Ripley's R windows package builds.

<h4>Installing From Binary</h4>
<dl>
  <dt> Change directory to the location in which you want to
       install the library. This is usually R_HOME/library.
  <dd>
  <dt> Download the zip file <a href="http://www.stats.ox.ac.uk/pub/RWin/@ZIP_FILE@">@ZIP_FILE@.</a>
  <dd>

  <dt> Unzip the contents of the zip file.
  <dd>
      <code>unzip @ZIP_FILE@</code>

  <dt> Download the <a
      href="http://www.fh-frankfurt.de/~igor/projects/libxml/index.html">
      libxml2-2.4.13 distribution for Windows</a> created by Igor Zlatkovic.
  <dd> You will possibly need the iconv libraries also.
  <dt> Install the libxml2 (and iconv) libraries into a directory
      and add that to your PATH.
  <dd>

  <dt> Run R and load the library using
      <code>library(XML)</code>!
  <dd>
</dl>

<h4>Installing From Source on Windows</h4>

To install from source, you can follow these steps.
<ul>
  <li> Change directory to the src/library/ within the R distribution.
      <br>
      <code>cd R_HOME/src/library</code>
  <li> Untar the @TAR_FILE@.
      <br>
        <code>tar zxf @TAR_FILE@</code>
  <li> Edit the <b>Makevars.win</b>
      file in the <code>XML/src/</code> directory.
      You will need to provide the names of the directories
      in which the libxml2 header files and the libxml2 library
      can be found.
      
  <li> Change directory to the src/gnuwin32 directory within the R
      distribution.
      <br>
      <code>cd ../gnuwin32</code>
  <li> Issue the pacakge build command
      <code>make pkg-XML</code>
</ul>


<h2><a name="FileList">File List</a></h2>
<table border="1">
<tr align="left"><td>File</td><td>Description</td></tr>
<tr align="left"><th>DocParse</th><th>parser using libxml.</th></tr>

<tr align="left"><th>EventParse</th><th> parser using expat.</th></tr>
<tr align="left"><th>RSCommon</th><th>File that 
    allows us to use the same code for R and S4/Splus5 by hiding the
    differences between these two via C pre-processor macros.
    This file is copied from $OMEGA_HOME/Interfaces/CORBA/CORBAConfig</th></tr>
<tr align="left"><th>Utils</th><th>routines shared by both files above
    for handling white space in text.</th></tr>
<tr align="left"><th>RS_XML.h</th><th>name space macro for routines used
    to avoid  conflicts with routine names with other
    libraries.</th></tr>
<tr align="left"><th>RSDTD</th><th>Routines for converting DTDs to
    user-level objects.</th></tr>
<tr align="left"><th>GNUmakefile</th><th>makefile controlling the
    compilation of the shared libraries, etc.
</th></tr>
<tr align="left"><th>expat/</th><th> makefiles that can be copied into expat distribution to make shared
               libraries for use here.</th></tr>  
<tr align="left"><th>libxml/</th><th>makefiles that can be copied into libxml distribution to make shared 
               library</th></tr>
<tr align="left"><th> Src/</th><th>R/S functions for parsing XML documents/buffers.</th></tr>


<tr align="left"><th>man/</th><th>R documentation for R/S functions.</th></tr>
<tr align="left"><th>Docs/</th><th>document (in noweb) describing initial ideas.</th></tr>
<tr align="left"><th>data/</th><th>example functions, closure
    definitions, DTDs, etc that are not quite official functions.</th></tr>    
</table>



<h2><a name="OtherInstalls">Installing libxml and/or Expat</a></h2>

The following information helps in installing the 3rd party libraries.
The approach is optional, but the need is to build shared libraries.
GNU makefiles are provided (in the subdirectories <code>expat/</code>
and <code>libxml/</code> of this distribution) to perform the
necessary operations. A simple way to place these in the
appropriate distribution  is to give the command, 
<pre>
     make LIBEXPAT=/dir/subdir expat
</pre>
and
<pre>
     make LIBXML=/dir/subdir libxml
</pre>

These requires <a href="http://www.gnu.org/order/ftp.html">GNU make</a> to be installed. 
<p />

<font color="red">These makefiles circumvents the regular Makefiles in the
        distributions.
</font>

<h3><a name="Expat">Installing Expat.</a></h3>
<ol>
  <li> Unzip the <a href="ftp://ftp.jclark.com/pub/xml/expat.zip">exapt.zip</a>
      file.   This will create a directory <code
      class="dir">expat/</code>.
  </li>

  <li> Copy the contents of the directory named expat within the
  directory where you are reading this installation file. There should be 4 files
  in total that are copied.  Two of these GNUmakefile and GNUmakefile.lib go into
  expat/. There are two others, one in each of xmltok and xmlparse that should
  be copied to the corresponding directories in the expat
      distribution.
<br />
 You can do this via the command
      <pre>
make LIBEXPAT=/wherever expat
      </pre>
<br />
issued from this directory.
      <p/>
Before doing this,  you will have to edit these files to ensure that the correct
  values are used for compiling shared libraries. At present, there are 
  settings for gcc and Solaris compilers.      
Edit the file <code>expat/GNUmakefile.lib</code>
and comment out the settings that do not apply to your machine.
Specifically, if you are using the GNU compiler (gcc),
comment out the two lines for the Solaris compilers
(the second settings for <code>PIC_FLAG</code> and <code>PIC_LD_FLAG</code>)      

 </li>
  <li> Change directory to the expat/ distribution.
 </li>
  <li> Type make.
 </li>      
</ol>



<h3><a name="libxml">Installing libxml</a></h3>
The steps are similar to those for <a href="#Expat">expat</a>.
<font color="red">
However, when compiling this for use with Splus5/S4, there are
<a href="libxmlWithS">additional steps</a>. Please follow these or you will likely see
segmentation faults, etc. due to conflicting symbols.
</font>

<ol>
  <li> Untar the <a href="http://rpmfind.net/veillard/XML/">libxml</a>
      distribution, creating a directory called, say,
       <code class="dir">libxml/</code>.
</li>
  <li> Copy the single GNUmakefile in the directory below this one (where you are reading this file)
   named <code class="dir">libxml/</code> to the location you have
      installed the libxml distribution.
<br/>
 You can do this via the command
      <pre>
make LIBXML=/wherever libxml      
      </pre>
<hr/>
<br/>
 You will have to edit these files to ensure that the correct
  values are used for compiling shared libraries. At present, there are 
  settings for gcc and Solaris compilers.
</li>
  <li> Change directory back to the libxml distribution.
</li>      

  <li> Type <code>./configure</code>.
</li>
      
  <li> Type <code>make</code>.
</li>      
</ol>

An alternative to this involves the following steps.
It has not been extensively tested at all.

<ol>
 <li> Apply the patch in the directory <code class="dir">libxml/</code>
   to the libxml directory.
   This can be done via the commands.
<pre>
  cd libxml
  make LIBXML=/wherever/installed  patch
</pre>
 <li> Append the following lines to 
 either Makefile.in or Makefile in the libxml distribution
(depending on whether you have alread configured that distribution
and/or whether you want the changes to persist across reconfigurations).

<pre>
libxml.so : $(OBJS)
	$(CC) $(SHARED_LD_FLAGS) -o $@  $(OBJS)

Cflags:
	@echo $(CFLAGS)
</pre>

 <li> Now, in that libxml distribution directory, issue the command:
<pre>
 make libxml.so CFLAGS="-fpic `make Cflags`" SHARED_LD_FLAGS=-shared 
</pre>
</ol>


<h4><a name="libxmlWithS">Compiling libxml for use with Splus5/S4</a></h4>

Both S4 and libxml have a symbol attribute. Because of the way
dynamically loaded code resolves symbols, the libxml facilities will
use the one from S4, incorrectly.  Until we determine the appropriate
linker flags, please modify the three references to attribute in
libxml <i>before</i> compiling the shared libraries.
The following patch makes the changes.
Apply them by invoking the
<pre>
 make libxmlpatch
</pre>
This
<pre>
 (PWD=`pwd`; export PWD ; cd $(LIBXML) ; patch -f &lt;  $(PWD)/libxml/PATCH.libxml)
</pre>
This works with the GNU patch.


<h3><a name="Features">Features</a></h3>

<ul>
  <li> Event driven style allowing complete control
       of data structure generated <i>as</i> the document
       is being read.
</li>
  <li> Document based style where entire XML tree is generated
       and traversed, with user-level functions generating
       nodes in resulting R data structure.
</li>      
  <li> Parsing of files or strings containg XML text,
       allowing the contents of remote files to be loaded
       in a separate step.
 </li>

  <li> Namespace access at user-level.
      </li>
      
  <li> User-level access to DTDs.

  <li> The libxml facilities support reading from compressed files.
</li>
</ul>

<h3><a name="RecentChanges">Recent Changes</a></h3>
<ul>
  <li> Added names to the children field from an XMLNode in <code>xmlTreeParse()</code>.
      </li>
  <li> Simple example of reading a Gnumeric worksheet.
      </li>
  <li> Fix up special case for trim when string is of length 1.
      </li>
</ul>

<hr />
<address><a href="http://www.stat.ucdavis.edu/~duncan">Duncan Temple Lang</a>
<a href="mailto:duncan@wald.ucdavis.edu">&lt;duncan@wald.ucdavis.edu&gt;</a></address>
<!-- hhmts start --><b>
Last modified: Mon Dec 13 21:28:37 EST 1999
</b><!-- hhmts end -->
</body> </html>
