Tools for parsing and generating XML within R and S-Plus.

Tools for parsing and generating XML within R and S-Plus. [R logo]

Help pages for package `XML' version 1.6-3

A C D E F G H L N P S T U X misc

.InitSAXMethods Generic Methods for SAX callbacks

-- A --

addNode | Add a node to a tree
append.XMLNode | Add children to an XML node
append.xmlNode | Add children to an XML node
asXMLNode | Converts non-XML node objects to XMLTextNode objects
asXMLTreeNode | Convert a regular XML node to one for use in a "flat" tree

-- C --

catalogResolve | Look up an element via the XML catalog mechanism
coerce,Doctype,character-method | Constructor for DTD reference
coerce,XMLInternalNode,XMLNode-method | Converts non-XML node objects to XMLTextNode objects
comment.SAX | Generic Methods for SAX callbacks
comment.SAX,ANY,SAXState-method | Generic Methods for SAX callbacks

-- D --

Doctype | Constructor for DTD reference
Doctype-class | Class to describe a reference to an XML DTD
dtdElement | Gets the definition of an element or entity from a DTD.
dtdElementValidEntry | Determines whether an XML element allows a particular type of sub-element.
dtdEntity | Gets the definition of an element or entity from a DTD.
dtdIsAttribute | Query if a name is a valid attribute of a DTD element.
dtdValidElement | Determines whether an XML tag is valid within another.

-- E --

endElement.SAX | Generic Methods for SAX callbacks
endElement.SAX,ANY,SAXState-method | Generic Methods for SAX callbacks
entityDeclaration.SAX | Generic Methods for SAX callbacks
entityDeclaration.SAX,ANY,ANY,ANY,ANY,ANY,SAXState-method | Generic Methods for SAX callbacks

-- F --

free | Release the specified object and clean up its memory usage
free,XMLInternalDocument-method | Release the specified object and clean up its memory usage

-- G --

genericSAXHandlers | SAX generic callback handler list
getNodeSet | Find matching nodes in an internal XML tree/DOM

-- H --

htmlTreeParse XML Parser

-- L --

length.XMLNode | Determine the number of children in an XMLNode object.
libxmlVersion | Get the version of the libxml library.

-- N --

names.XMLNode | Get the names of an XML nodes children.
newXMLDoc | Create internal XML node or document object
newXMLNode | Create internal XML node or document object

-- P --

parseDTD | Read a Document Type Definition (DTD)
parseURI | Parse a URI string into its elements
print.XMLAttributeDef | Methods for displaying XML objects
print.XMLCDataNode | Methods for displaying XML objects
print.XMLComment | Methods for displaying XML objects
print.XMLElementContent | Methods for displaying XML objects
print.XMLElementDef | Methods for displaying XML objects
print.XMLEntity | Methods for displaying XML objects
print.XMLEntityRef | Methods for displaying XML objects
print.XMLNode | Methods for displaying XML objects
print.XMLOrContent | Methods for displaying XML objects
print.XMLProcessingInstruction | Methods for displaying XML objects
print.XMLSequenceContent | Methods for displaying XML objects
print.XMLTextNode | Methods for displaying XML objects
processingInstruction.SAX | Generic Methods for SAX callbacks
processingInstruction.SAX,ANY,ANY,SAXState-method | Generic Methods for SAX callbacks

-- S --

saveXML | Output internal XML Tree
SAXState-class | A virtual base class defining methods for SAX parsing
startElement.SAX | Generic Methods for SAX callbacks
startElement.SAX,ANY,ANY,SAXState-method | Generic Methods for SAX callbacks
supportsExpat | Determines which native XML parsers are being used.
supportsLibxml | Determines which native XML parsers are being used.

-- T --

text.SAX | Generic Methods for SAX callbacks
text.SAX,ANY,SAXState-method | Generic Methods for SAX callbacks
toString.XMLNode | Creates string representation of XML node

-- U --

URI-class Parse a URI string into its elements

-- X --

xmlApply | Applies a function to each of the children of an XMLNode
xmlAttributeType | The type of an XML attribute for element from the DTD
xmlAttrs | Get the list of attributes of an XML node.
xmlCDataNode | Create an XML node
xmlChildren | Gets the sub-nodes within an XMLNode object.
xmlCommentNode | Create an XML node
xmlContainsElement | Checks if an entity is defined within a DTD.
xmlContainsEntity | Checks if an entity is defined within a DTD.
xmlDOMApply | Apply function to nodes in an XML tree/DOM.
xmlElementsByTagName | Retrieve the children of an XML node with a specific tag name
xmlEventHandler | Default handlers for the SAX-style event XML parser
xmlEventParse | XML Event/Callback element-wise Parser
xmlFlatListTree | Constructors for trees stored as flat list of nodes with information about parents and children.
xmlGetAttr | Get the value of an attribute in an XML node
xmlHandler | Example XML Event Parser Handler Functions
xmlHashTree | Constructors for trees stored as flat list of nodes with information about parents and children.
XMLInternalDocument-class | Class to represent reference to C-level data structure for an XML document
XMLInternalElementNode-class | Classes to describe an XML node object.
XMLInternalNode-class | Classes to describe an XML node object.
xmlName | Extraces the tag name of an XMLNode object.
xmlNamespace | Retrieve the namespace value of an XML node.
XMLNamespace-class | Retrieve the namespace value of an XML node.
xmlNamespace.XMLInternalNode | Retrieve the namespace value of an XML node.
xmlNamespace.XMLNode | Retrieve the namespace value of an XML node.
xmlNamespaceDefinitions | Get definitions of any namespaces defined in this XML node
xmlNode | Create an XML node
XMLNode-class | Classes to describe an XML node object.
xmlOutputBuffer | XML output streams
xmlOutputDOM | XML output streams
xmlParent | Get parent node of XMLInternalNode
xmlPINode | Create an XML node
xmlRoot | Get the top-level XML node.
xmlSApply | Applies a function to each of the children of an XMLNode
xmlSize | The number of sub-elements within an XML node.
xmlTextNode | Create an XML node
xmlTree | An internal, updatable DOM object for building XML trees
xmlTreeParse | XML Parser
xmlValue | Extract the contents of a leaf XML node
xpathApply | Find matching nodes in an internal XML tree/DOM

-- misc --

[.XMLNode | Convenience accessors for the children of XMLNode objects.
[[.XMLDocumentContent | Convenience accessors for the children of XMLNode objects.
[[.XMLNode | Convenience accessors for the children of XMLNode objects.


Add a node to a tree

Description

This generic function allows us to add a node to a tree for different types of trees. Currently it just works for XMLHashTree, but it could be readily extended to the more general XMLFlatTree class. However, the concept in this function is to change the tree and return the node. This does not work unless the tree is directly mutable without requiring reassignment, i.e. the changes do not induce a new copy of the original tree object. DOM trees which are lists of lists of lists do not fall into this category.

Usage

addNode(node, parent, to)

Arguments

node | the node to be added as a child of the parent.
parent | the parent node or identifier
to | the tree object

Value

The new node object. For flat trees, this will be the node after it has been coerced to be compatible with a flat tree, i.e. has an id and the host tree added to it.

Author(s)

Duncan Temple Lang

References

http://www.w3.org

See Also

xmlHashTree asXMLTreeNode

Examples

  tt = xmlHashTree()

  top = addNode(xmlNode("top"), character(), tt)
  addNode(xmlNode("a"), top, tt)
  b = addNode(xmlNode("b"), top, tt)
  c = addNode(xmlNode("c"), b, tt)
  addNode(xmlNode("c"), top, tt)
  addNode(xmlNode("c"), b, tt)
  addNode(xmlTextNode("Some text"), c, tt)

  xmlElementsByTagName(tt$top, "c")

  tt
[Package XML version 1.6-3 Index]


Add children to an XML node

Description

This appends one or more XML nodes as children of an existing node.

Usage

append.XMLNode(to, ...)
append.xmlNode(to, ...)

Arguments

to | the XML node to which the sub-nodes are to be added.
... | the sub-nodes which are to be added to the to node. If this is a list of XMLNode objects (e.g. create by a call to lapply), then that list is used.

Value

The original to node containing its new children nodes.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

[<-.XMLNode [[<-.XMLNode [.XMLNode [[.XMLNode

Examples

  # Create a very simple representation of a simple dataset.
  # This is just an example. The result is
   # <data numVars="2" numRecords="3">
   # <varNames>
   #  <string>
   #   A
   #  </string>
   #  <string>
   #   B
   #  </string>
   # </varNames>
   # <record>
   #  1.2 3.5
   # </record>
   # <record>
   #  20.2 13.9
   # </record>
   # <record>
   #  10.1 5.67
   # </record>
   # </data>

 n = xmlNode("data", attrs = c("numVars" = 2, numRecords = 3))
 n = append.xmlNode(n, xmlNode("varNames", xmlNode("string", "A"), xmlNode("string", "B")))
 n = append.xmlNode(n, xmlNode("record", "1.2 3.5"))
 n = append.xmlNode(n, xmlNode("record", "20.2 13.9"))
 n = append.xmlNode(n, xmlNode("record", "10.1 5.67"))

 print(n)

## Not run:
   tmp <-  lapply(references, function(i) {
                                  if(!inherits(i, "XMLNode"))
                                    i <- xmlNode("reference", i)
                                  i
                              })

   r <- xmlNode("references")
   r[["references"]] <- append.xmlNode(r[["references"]], tmp)
## End(Not run)


Assign sub-nodes to an XML node

Description

These functions allow one to assign a sub-node to an existing XML node by name or index. These are the assignment equivalents of the subsetting accessor functions. They are typically called indirectly via the assignment operator, such as x[["myTag"]] <- xmlNode("mySubTag").

Usage

x[i] <- value
"[<-.XMLNode"(x, i, value)
"[[<-.XMLNode"(x, i, value)

Arguments

x | the XMLNode object to which the sub-node is to be assigned.
i | the identifier for the position in the list of children of x into which the right-hand-side node(s) should be assigned. These can be either numbers or names.
value | one or more XMLNode objects which are to be the sub-nodes of x.

Value

The XML node x containing the new or modified nodes.

Author(s)

Duncan Templle Lang

References

http://www.w3.org, http://www.omegahat.org/RSXML

See Also

[.XMLNode [[.XMLNode append.xmlNode xmlSize

Examples

 top <- xmlNode("top", xmlNode("next","Some text"))
 top[["second"]] <- xmlCDataNode("x <- 1:10")
 top[[3]] <- xmlNode("tag",attrs=c(id="name"))


Converts non-XML node objects to XMLTextNode objects

Description

This function is used to convert S objects that are not already XMLNode objects into objects of that class. Specifically, it treats the object as a string and creates an XMLTextNode object.

Also, there is a method for converting an XMLInternalNode - the C-level libxml representation of a node - to an explicit R-only object which contains the R values of the data in the internal node.

Usage

asXMLNode(x)

Arguments

x the object to be converted to an XMLNode object. This is typically alread an object that inherits from XMLNode or a string.

Value

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlNode xmlTextNode

Examples

   # creates an XMLTextNode.
 asXMLNode("a text node")

   # unaltered.
 asXMLNode(xmlNode("p"))


Convert a regular XML node to one for use in a "flat" tree

asXMLTreeNode(XML) R Documentation

Convert a regular XML node to one for use in a 'flat' tree

Description

This coerces a regular R-based XML node (i.e. not an internal C-level node) to a form that can be inserted into a flat tree, i.e. one that stores the nodes in a non-hierarchical manner. It is thus used in conjunction with xmlHashTree and xmlFlatListTree. It adds id and env fields to the node and specializes the class by prefixing className to the class attribute.

Usage

asXMLTreeNode(node, env, id = get(".nodeIdGenerator", env)(xmlName(node)), className = "XMLTreeNode")

Arguments

node | the original XML node
env | the XMLFlatTree object into which this node will be inserted.
id | the identifier for the node in the flat tree. If this is not specified, we consult the tree itself and its built-in identifier generator. By default, the name of the node is used as its identifier unless there is another node with that name.
className | a vector of class names to be prefixed to the existing class vector of the node.

Value

An object of class className, i.e. by default "XMLTreeNode".

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML

See Also

xmlHashTree xmlFlatListTree

Examples

[Package XML version 1.6-3 Index]


Look up an element via the XML catalog mechanism

Description

XML parsers use a catalog to map generic system and public addresses to actual local files or potentially different remote files. We can use a catalog to map a reference such as http://www.omegahat.org/XSL/ to a particular directory on our local machine and then not have to modify any of the documents if we move the local files to another directory, e.g. install a new version in an alternate directory.

This function provides a mechanism to query the catalog to resolve a URI, PUBLIC or SYSTEM identifier.

Usage

catalogResolve(id, type = "uri", debug = FALSE)

Arguments

id | the name of the (generic) element to be resolved
type | a string, specifying whether the lookup is for a uri, system or public element
debug | logical value indicating whether to turn on debugging output written to the console (TRUE) or not (FALSE).

Details

Value

A character vector. If the element was resolved, the single element is the resolved value. Otherwise, the character vector will contain no elements.

Author(s)

Duncan Temple Lang

References

http://www.xmlsoft.org http://www.sagehill.net/docbookxsl/Catalogs.html provides a short, succinct tutorial on catalogs.

See Also

xmlTreeParse

Examples

Sys.putenv("XML_CATALOG_FILES" = system.file("exampleData", "catalog.xml", package = "XML"))

catalogResolve("-//OASIS//DTD DocBook XML V4.4//EN", "public")

catalogResolve("http://www.omegahat.org/XSL/foo.xsl")

catalogResolve("http://www.omegahat.org/XSL/article.xsl", "uri")
catalogResolve("http://www.omegahat.org/XSL/math.xsl", "uri")

  # This one does not resolve anything, returning an empty value.
catalogResolve("http://www.oasis-open.org/docbook/xml/4.1.2/foo.xsl", "uri")


Constructor for DTD reference

Description

This is a constructor for the Doctype class that can be provided at the top of an XML document to provide information about the class of document, i.e. its DTD or schema. Also, there is a method for converting such a Doctype object to a character string.

Usage

Doctype(system = character(), public = character(), name = "")

Arguments

system | the system URI that locates the DTD.
public | the identifier for locating the DTD in a catalog, for example. This should be a character vector of length 2, giving the public identifier and a URI. If just the public identifier is given and a string is given for system argument, the system value is used as the second element of public. The public identifer should be of the form +//creator//name//language where the first element is either + or -, and the language is described by a code in the ISO 639 document.
name | the name of the root element in the document. This should be the first parameter, but is left this way for backward compatability. And

Value

An object of class Doctype.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML XML Elements of Style, Simon St. Laurent.

See Also

saveXML

Examples

  d = Doctype(name = "section", public = c("-//OASIS//DTD DocBook XML V4.2//EN", "http://oasis-open.org/docbook/xml/4.2/docbookx.dtd"))
  as(d, "character")

   # this call switches the system to the URI associated with the PUBLIC element.
  d = Doctype(name = "section", public = c("-//OASIS//DTD DocBook XML V4.2//EN"), system = "http://oasis-open.org/docbook/xml/4.2/docbookx.dtd")


Class to describe a reference to an XML DTD

Description

This class is intended to identify a DTD by SYSTEM file and/or PUBLIC catalog identifier. This is used in the DOCTYPE element of an XML document.

Objects from the Class

Objects can be created by calls of the form new("Doctype", ...). or Doctype.

Slots

name:
Object of class "character". This is the name of the top-level element in the XML document.
system:
Object of class "character". This is the name of the file on the system where the DTD document can be found. Can this be a URI?
public:
Object of class "character". This gives the PUBLIC identifier for the DTD that can be searched for in a catalog, for example to map the DTD reference to a local system element.

Methods

No methods defined with class "Doctype" in the signature.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org

See Also

Doctype saveXML

Examples
[Package XML version 1.6-3 Index]


Gets the definition of an element or entity from a DTD.

Description

A DTD in R consists of both element and entity definitions. These two functions provide simple access to individual elements of these two lists, using the name of the element or entity. The DTD is provided to determine where to look for the entry.

Usage

dtdElement(name,dtd)
dtdEntity(name,dtd)

Arguments

name | The name of the element being retrieved/acessed.
dtd | The DTD from which the element is to be retrieved.

Details

An element within a DTD contains both the list of sub-elements it can contain and a list of attributes that can be used within this tag type. dtdElement retrieves the element by name from the specified DTD definition. Entities within a DTD are like macros or text substitutes used within a DTD and/or XML documents that use it. Each consists of a name/label and a definition, the text that is substituted when the entity is referenced. dtdEntity retrieves the entity definition from the DTD. \ One can read a DTD directly (using parseDTD) or implicitly when reading a document (using xmlTreeParse) The names of all available elements can be obtained from the expression names(dtd$elements). This function is simply a convenience for indexing this elements list.

Value

An object of class XMLElementDef.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

parseDTD, dtdValidElement

Examples

 dtdFile <- system.file("exampleData","foo.dtd", package="XML")
 foo.dtd <- parseDTD(dtdFile)

   # Get the definition of the `entry1' element
 tmp <- dtdElement("variable", foo.dtd)
 xmlAttrs(tmp)

 tmp <- dtdElement("entry1", foo.dtd)

  # Get the definition of the `img' entity
 dtdEntity("img", foo.dtd)


Determines whether an XML element allows a particular type of sub-element.

Description

This tests whether name is a legitimate tag to use as a direct sub-element of the element tag according to the definition of the element element in the specified DTD. This is a generic function that dispatches on the element type, so that different version take effect for XMLSequenceContent, XMLOrContent, XMLElementContent.

Usage

dtdElementValidEntry(element, name, pos=NULL)

Arguments

element | The XMLElementDef defining the tag in which we are asking whether the sub-element can be used.
name | The name of the sub-element about which we are querying the list of sub-tags within element.
pos | An optional argument which, if supplied, queries whether the name sub-element is valid as the pos-th child of element.

Details

This is not intended to be called directly, but indirectly by the dtdValidElement function.

Value

Logical value indicating whether the sub-element can appear in an element tag or not.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

parseDTD, dtdValidElement, dtdElement

Examples

 dtdFile <- system.file("exampleData", "foo.dtd",package="XML")
 dtd <- parseDTD(dtdFile)

  dtdElementValidEntry(dtdElement("variables",dtd), "variable")


Query if a name is a valid attribute of a DTD element.

Description

Examines the definition of the DTD element definition identified by element to see if it supports an attribute named name.

Usage

dtdIsAttribute(name, element, dtd)

Arguments

name | The name of the attribute being queried
element | The name of the element whose definition is to be used to obtain the list of valid attributes.
dtd | The DTD containing the definition of the elements, specifically element.

Details

Value

A logical value indicating if the list of attributes suppported by the specified element has an entry named name. This does indicate what type of value that attribute has, whether it is required, implied, fixed, etc.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

parseDTD, dtdElement, xmlAttrs

Examples

 dtdFile <- system.file("exampleData", "foo.dtd", package="XML")
 foo.dtd <- parseDTD(dtdFile)

    # true
  dtdIsAttribute("numRecords", "dataset", foo.dtd)

    # false
  dtdIsAttribute("date", "dataset", foo.dtd)


Determines whether an XML tag is valid within another.

Description

This tests whether name is a legitimate tag to use as a direct sub-element of the within tag according to the definition of the within element in the specified DTD.

Usage

dtdValidElement(name, within, dtd, pos=NULL)

Arguments

name | The name of the tag which is to be inserted inside the within tag.
within | The name of the parent tag the definition of which we are checking to determine if it contains name.
dtd | The DTD in which the elements name and within are defined.
pos | An optional position at which we might add the name element inside within. If this is specified, we have a stricter test that accounds for sequences in which elements must appear in order. These are comma-separated entries in the element definition.

Details

This applies to direct sub-elements or children of the within tag and not tags nested within children of that tag, i.e. descendants.

Value

Returns a logical value. TRUE indicates that a name element can be used inside a within element. FALSE indicates that it cannot.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

parseDTD, dtdElement, dtdElementValidEntry,

Examples

 dtdFile <- system.file("exampleData", "foo.dtd", package="XML")
 foo.dtd <- parseDTD(dtdFile)

  # The following are true.
 dtdValidElement("variable","variables", dtd = foo.dtd)
 dtdValidElement("record","dataset", dtd = foo.dtd)

  # This is false.
 dtdValidElement("variable","dataset", dtd = foo.dtd)


Release the specified object and clean up its memory usage

Description

This generic function is available for explicitly releasing the memory associated with the given object. It is intended for use on external pointer objects which do not have an automatic finalizer function/routine that cleans up the memory that is used by the native object. This is the case, for example, for an XMLInternalDocument. We cannot free it with a finalizer in all cases as we may have a reference to a node in the associated document tree. So the user must explicitly release the XMLInternalDocument object to free the memory it occupies.

Usage

free(obj)

Arguments

obj the object whose memory is to be released, typically an external pointer object or object that contains a slot that is an external pointer.

Details

The methods will generally call a C routine to free the native memory.

Value

An updated version of the object with the external address set to NIL. This is up to the individual methods.

Author(s)

Duncan Temple Lang

References

See Also

xmlTreeParse with useInternalNodes = TRUE

Examples

 f = system.file("exampleData", "boxplot.svg", package = "XML")
 doc = xmlTreeParse(f, useInternalNodes = TRUE)
 nodes = getNodeSet(doc, "//path")
 rm(nodes)
 free(doc)


SAX generic callback handler list

Description

This is a convenience function to get the collection of generic functions that make up the callbacks for the SAX parser. The return value can be used directly as the value of the handlers argument in xmlEventParse. One can easily specify a subset of the handlers by giving the names of the elements to include or exclude.

Usage

genericSAXHandlers(include, exclude)

Arguments

include | if supplied, this gives the names of the subset of elements to return.
exclude | if supplied (and include is not), this gives the names of the elements to remove from the list of functions.

Value

A list of functions. By default, the elements are named startElement, endElement, comment, text, processingInstruction, entityDeclaration and contain the corresponding generic SAX callback function, i.e. given by the element name with the .SAX suffix.
If include or exclude is specified, a subset of this list is returned.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlEventParse startElement.SAX endElement.SAX comment.SAX processingInstruction.SAX entityDeclaration.SAX .InitSAXMethods

Examples
[Package XML version 1.6-3 Index]


Find matching nodes in an internal XML tree/DOM

Description

These functions provide a way to find XML nodes that match a particular criterion. It uses the XPath syntax and allows quite powerful expressions for identifying nodes. The XPath language requires some knowledge, but tutorials are available on the Web and in books. XPath queries can result in different types of values such as numbers, strings, and node sets.

These sets of matching nodes are returned in R as a list. And then one can iterate over these elements to process the nodes in whatever way one wants. Unfortunately, this involves two loops - one in the XPath query over the entire tree, and another in R. Typically, this is fine as the number of matching nodes is reasonably small. However, if repeating this on numerous files, speed may become an issue. We can avoid the second loop (i.e. the one in R) by applying a function to each node before it is returned to R as part of the node set. The result of the function call is then returned, rather than the node itself.

One can provide an expression rather than a function. This is expected to be a call and the first argument of the call will be replaced with the node.

Usage

getNodeSet(doc, path, namespaces = getDefaultNamespace(xmlRoot(doc)), fun = NULL, ...)
xpathApply(doc, path, fun, ... , namespaces = getDefaultNamespace(xmlRoot(doc)))

Arguments

doc | an object of class XMLInternalDocument
path | a string (character vector of length 1) giving the XPath expression to evaluate.
namespaces | a named character vector giving the namespace prefix and URI pairs that are to be used in the XPath expression and matching of nodes. The prefix is just a simple string that acts as a short-hand or alias for the URI that is the unique identifier for the namespace. The URI is the element in this vector and the prefix is the corresponding element name. One only needs to specify the namespaces in the XPath expression and for the nodes of interest rather than requiring all the namespaces for the entire document. Also note that the prefix used in this vector is local only to the path. It does not have to be the same as the prefix used in the document to identify the namespace. However, the URI in this argument must be identical to the target namespace URI in the document. It is the namespace URIs that are matched (exactly) to find correspondence. The prefixes are used only to refer to that URI.
fun | a function object, or an expression or call, which is used when the result is a node set and evaluated for each node element in the node set. If this is a call, the first argument is replaced with the current node.
... | any additional arguments to be passed to fun for each node in the node set.

Details

This calls the libxml routine xmlXPathEval.

Value

The results can currently be different based on the returned value from the XPath expression evaluation:

list | a node set
numeric | a number
logical | a boolean
character | a string, i.e. a single character element.

If fun is supplied and the result of the XPath query is a node set, the result in R is a list.

Note

In order to match nodes in the default name space for documents with a non-trivial default namespace, e.g. given as xmlns="http://www.omegahat.org", you will need to use a prefix for the default namespace in this call. When specifying the namespaces, give a name - any name - to the default namespace URI and then use this as the prefix in the XPath expression, e.g. getNodeSet(d, "//d:myNode", c(d = "http://www.omegahat.org")) to match myNode in the default name space http://www.omegahat.org.

This default namespace of the document is now computed for us and is the default value for the namespaces argument. It can be referenced using the prefix 'd', standing for default but sufficiently short to be easily used within the XPath expression.

More of the XPath functionality provided by libxml can and may be made available to the R package. Facilities such as compiled XPath expressions, functions, ordered node information are examples.

Please send requests to the package maintainer.

Author(s)

Duncan Temple Lang <duncan@wald.ucdavis.edu>

References

http://xmlsoft.org, http://www.w3.org/xml http://www.w3.org/TR/xpath http://www.omegahat.org/RSXML

See Also

xmlTreeParse with useInternalNodes as TRUE.

Examples

 doc = xmlTreeParse(system.file("exampleData", "tagnames.xml", package = "XML"), useInternalNodes = TRUE)
 getNodeSet(doc, "/doc//b[@status]")
 getNodeSet(doc, "/doc//b[@status='foo']")

 els = getNodeSet(doc, "/doc//a[@status]")
 sapply(els, function(el) xmlGetAttr(el, "status"))

  # Using a namespace
 f = system.file("exampleData", "SOAPNamespaces.xml", package = "XML")
 z = xmlTreeParse(f, useInternal = TRUE)
 getNodeSet(z, "/a:Envelope/a:Body", c("a" = "http://schemas.xmlsoap.org/soap/envelope/"))
 getNodeSet(z, "//a:Body", c("a" = "http://schemas.xmlsoap.org/soap/envelope/"))

  # Get two items back with namespaces
 f = system.file("exampleData", "gnumeric.xml", package = "XML")
 z = xmlTreeParse(f, useInternal = TRUE)
 getNodeSet(z, "//gmr:Item/gmr:name", c(gmr="http://www.gnome.org/gnumeric/v2"))

 #####
 # European Central Bank (ECB) exchange rate data

  # Data is available from "http://www.ecb.int/stats/eurofxref/eurofxref-hist.xml"
  # or locally.

 uri = system.file("exampleData", "eurofxref-hist.xml.gz", package = "XML")
 doc = xmlTreeParse(uri, useInternalNodes = TRUE)

   # The default namespace for all elements is given by
 namespaces <- c(ns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref")

     # Get the data for Slovenian currency for all time periods.
     # Find all the nodes of the form <Cube currency="SIT"...>

 slovenia = getNodeSet(doc, "//ns:Cube[@currency='SIT']", namespaces )

    # Now we have a list of such nodes, loop over them
    # and get the rate attribute
 rates = as.numeric( sapply(slovenia, xmlGetAttr, "rate") )
    # Now put the date on each element
    # find nodes of the form <Cube time=".." ... >
    # and extract the time attribute
 names(rates) = sapply(getNodeSet(doc, "//ns:Cube[@time]", namespaces ),
                      xmlGetAttr, "time")

    #  Or we could turn these into dates with strptime()
 strptime(names(rates), "%Y-%m-%d")

   #  Using xpathApply, we can do
 rates = xpathApply(doc, "//ns:Cube[@currency='SIT']", xmlGetAttr, "rate", namespaces = namespaces )
 rates = as.numeric(unlist(rates))

   # Using an expression rather than  a function and ...
 rates = xpathApply(doc, "//ns:Cube[@currency='SIT']", quote(xmlGetAttr(x, "rate")), namespaces = namespaces )

   #
  uri = system.file("exampleData", "namespaces.xml", package = "XML")
  d = xmlTreeParse(uri, useInternalNodes = TRUE)
  getNodeSet(d, "//c:c", c(c="http://www.c.org"))

   # the following, perhaps unexpectedly but correctly, returns an empty
   # with no matches

  getNodeSet(d, "//defaultNs", "http://www.omegahat.org")

   # But if we create our own prefix for the evaluation of the XPath
   # expression and use this in the expression, things work as one
   # might hope.
  getNodeSet(d, "//dummy:defaultNs", c(dummy = "http://www.omegahat.org"))

   # And since the default value for the namespaces argument is the
   # default namespace of the document with the prefix 'd', we can use
  getNodeSet(d, "//d:defaultNs")

   # And the syntactic sugar is
  d["//d:defaultNs"]


Determine the number of children in an XMLNode object.

Description

This function is a simple way to compute the number of sub-nodes (or children) an XMLNode object possesses. It is provided as a convenient form of calling the xmlSize function.

Usage

 length.XMLNode(x)

Arguments

x the XMLNode object whose length is to be queried.

Value

An integer giving the number of sub-nodes of this node.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlSize xmlChildren

Examples

  doc <- xmlTreeParse(system.file("exampleData", "mtcars.xml", package="XML"))
  r <- xmlRoot(doc, skip=TRUE)
  length(r)
    # get the last entry
  r[[length(r)]]


Get the version of the libxml library.

Description

This currently retrieves the version of the libxml library used when installing this XML package.

Usage

libxmlVersion()

Details

This computes the version at compile time. In the future we will hopefully find a way to find the run-time version.

Value

A named list with fields

major | the major version number, either 1 or 2 indicating the old or new-style library.
minor | the within version release number.
patch | the within minor release version number

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org, http://www.omegahat.org

See Also

Examples

 ver <- libxmlVersion()
 if(is.null(ver)) {
   cat("Relly old version of libxml\n")
 } else {
   if(ver$major > 1) {
     cat("Using libxml2\n")
   }
 }


Get the names of an XML nodes children.

Description

This is a convenient way to obtain the XML tag name of each of the sub-nodes of a given XMLNode object.

Usage

names.XMLNode(x)

Arguments

x the XMLNode whose sub-node tag names are being queried.

Value

A character vector returning the tag names of the sub-nodes of the given XMLNode argument.

Note

This overrides the regular names method which would display the names of the internal fields of an XMLNode object. Since these are intended to be invisible and queried via the accessor methods (xmlName, xmlAttrs, etc.), this should not be a problem. If you textit{really} need the names of the fields, use names(unclass(x)).

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlApply xmlSApply

Examples

 doc <- xmlTreeParse(system.file("exampleData", "mtcars.xml", package="XML"))
 names(xmlRoot(doc))

 r <- xmlRoot(doc)
 r[names(r) == "variables"]


Create internal XML node or document object

Description

These are used to create internal `libxml' nodes and top-level document objects that are used to write XML trees. While the functions are available, their direct use is not encouraged. Instead, use xmlTree as the functions need to be used within a strict regime to avoid corrupting C level structures.

Usage

newXMLDoc(dtd, namespaces=NULL)
newXMLNode(name, ..., attrs = NULL, namespace="", doc=NULL)

Arguments

dtd | the name of the DTD to use for the XML document.
namespaces | a named character vector with each element specifying a name space identifier and the corresponding URI for that namespace that are to be declared and used in the XML document, \ e.g. c(shelp = "http://www.omegahat.org/XML/SHelp")
name | the tag/element name for the XML node
... | the children of this node. These can be other nodes created earlier or R strings that are converted to text nodes and added as children to this newly created node.
attrs | a named list of name-value pairs to be used as attributes for the XML node.
namespace | the short or alias for the namespace to use for this XML node
doc | the XMLInternalDocument object created with newXMLDoc that is used to root the node.

Details

These create internal C level objects/structure instances that can be added to a libxml DOM and subsequently inserted into other document objects or ``serialized'' to textual form.

Value

Each function returns an R object that points to the C-level structure instance. These are of class XMLInternalDocument and XMLInternalNode, respectively

Note

These functions are used to build up an internal XML tree. This can be used in the Sxslt package (http://www.omegahat.org/Sxslt) when creating content in R that is to be dynamicall inserted into an XML document.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org, http://www.omegahat.org

See Also

xmlTree saveXML

Examples
[Package XML version 1.6-3 Index]


Read a Document Type Definition (DTD)

Description

Represents the contents of a DTD as a user-level object containing the element and entity definitions.

Usage

parseDTD(extId, asText=FALSE, name="", isURL=FALSE)

Arguments

extId | The name of the file containing the DTD to be processed.
asText | logical indicating whether the value of `extId' is the name of a file or the DTD content itself. Use this when the DTD is read as a character vector, before being parsed and handed to the parser as content only.
name | Optional name to provide to the parsing mechanism.
isURL | A logical value indicating whether the input source is to be considred a URL or a regular file or string containing the XML.

Details

Parses and converts the contents of the DTD in the specified file into a user-level object containing all the information about the DTD.

Value

A list with two entries, one for the entities and the other for the elements defined within the DTD.

entities a named list of the entities defined in the DTD. Each entry is indexed by the name of the corresponding entity. Each is an object of class XMLEntity or alternatively XMLExternalEntity if the entity refers to an external definition. The fields of these types of objects are
name
the name of the entity by which users refer to it.
content
the expanded value or definition of the entity
original
the value of the entity, but with references to other entities not expanded, but maintained in symbolic form.
elements a named list of the elements defined in the DTD, with the name of each element being the identifier of the element being defined. Each entry is an object of class XMLElementDef which has 4 fields.
name
the name of the element.
type
a named integer indicating the type of entry in the DTD, usually either element or mixed. The name of the value is a user-level type. The value is used for programming, both internally and externally.
contents
a description of the elements that can be nested within this element. This is an object of class XMLElementContent or one of its specializations - XMLSequenceContent, XMLOrContent. Each of these encodes the number of such elements permitted (one, one or more, zero or one, or zero or more); the type indicating whether the contents consist of a single element type, an ordered sequence of elements, or one of a set of elements. Finally, the actual contents description is described in the elements field. This is a list of one or more XMLElementContent, XMLSequenceContent and XMLOrContent objects.
attributes
a named list of the attributes defined for this element in the DTD. Each element is of class XMLAttributeDef which has 4 fields.
name
name of the attribute, i.e. the left hand side
type
the type of the value, e.g. an CDATA, Id, Idref(s), Entity(s), NMToken(s), Enumeration, Notation
defaultType
the defined type, one of None, Implied, Fixed or Required.
defaultValue
the default value if it is specified, or the enumerated values as a character vector, if the type is Enumeration.

WARNING

Errors in the DTD are stored as warnings for programmatic access.

Note

Needs libxml (currently version 1.8.7) from

Author(s)

Duncan Temple Lang <duncan@wald.ucdavis.edu>

References

http://www.w3.org

See Also

xmlTreeParse, WritingXML.html in the distribution.

Examples

 dtdFile <- system.file("exampleData", "foo.dtd",package="XML")
 parseDTD(dtdFile)

    # Read from text
 txt <- readLines(dtdFile)
 txt <- paste(txt, "\n", collapse="")
 d <- parseDTD(txt, asText=TRUE)

## Not run:
 url <- "http://www.omegahat.org/XML/DTDs/DatasetByRecord.dtd"
 d <- parseDTD(url, asText=FALSE)
## End(Not run)


Parse a URI string into its elements

Description

This breaks a URI given as a string into its different elements such as protocol/scheme, host, port, file name, query. This information can be used, for example, when constructing URIs relative to a base URI.

The return value is an S3-style object of class URI.

This function uses libxml routines to perform the parsing.

Usage

parseURI(uri)

Arguments

uri a single string

Value

A list with 8 elements

scheme | the name of the protocol being used, http, ftp as a string.
authority | a string represeting a rarely used aspect of URIs
server | a string identifying the host, e.g. www.omegahat.org
user | a string giving the name of the user, e.g. in FTP "ftp://duncan@www.omegahat.org", this would yield "duncan"
path | a string identifying the path of the target file
query | the CGI query part of the string, e.g. the bit after '?' of the form name=value&name=value
fragment | a string giving the coo
port | an integer identifying the port number on which the connection is to be made

See Also

Examples

  parseURI("http://www.omegahat.org:8080/RCurl/index.html")
  parseURI("ftp://duncan@www.omegahat.org:8080/RCurl/index.html")


Methods for displaying XML objects

Description

These different methods attempt to provide a convenient way to display R objects representing XML elements when they are printed in the usual manner on the console, files, etc. via the print function. Each typically outputs its contents in the way that they would appear in an XML document.

Usage

print.XMLNode(x, ..., indent= "", tagSeparator = "\n")
print.XMLComment(x, ..., indent = "", tagSeparator = "\n")
print.XMLTextNode(x, ..., indent = "", tagSeparator = "\n")
print.XMLCDataNode(x, ..., indent="", tagSeparator = "\n")
print.XMLProcessingInstruction(x, ..., indent="", tagSeparator = "\n")
print.XMLAttributeDef(x, ...)
print.XMLElementContent(x, ...)
print.XMLElementDef(x, ...)
print.XMLEntity(x, ...)
print.XMLEntityRef(x, ..., indent= "", tagSeparator = "\n")
print.XMLOrContent(x, ...)
print.XMLSequenceContent(x, ...)

Arguments

x | the XML object to be displayed
... | additional arguments for controlling the output from print. Currently unused.
indent | a prefix that is emitted before the node to indent it relative to its parent and child nodes. This is appended with a space at each succesive level of the tree. If no indentation is desired (e.g. when xmlTreeParse is called with trim and ignoreBlanks being FALSE) and TRUE respectively, one can pass the value FALSE for this indent argument.
tagSeparator | when printing nodes, successive nodes and children are by default displayed on new lines for easier reading. One can specify a string for this argument to control how the elements are separated in the output. The primary purpose of this argument is to allow no space between the elements, i.e. a value of "".

Value

Currently, NULL.

Note

We could make the node classes self describing with information about whether ignoreBlanks was TRUE or FALSE and if trim was TRUE or FALSE. This could then be used to determine the appropriate values for indent and tagSeparator. Adding an S3 class element would allow this to be done without the addition of an excessive number of classes.

Author(s)

Duncan Temple Lang

References

http://www.w3.org, http://www.omegahat.org/RSXML

See Also

xmlTreeParse

Examples

  fileName <- system.file("exampleData", "event.xml", package ="XML")

     # Example of how to get faithful copy of the XML.
  doc = xmlRoot(xmlTreeParse(fileName, trim = FALSE, ignoreBlanks = FALSE))
  print(doc, indent = FALSE, tagSeparator = "")

     # And now the default mechanism
  doc = xmlRoot(xmlTreeParse(fileName))
  print(doc)


Output internal XML Tree

Description

Methods for writing the representation of an XML tree to a string or file. Originally this was intended to be used only for DOMs (Document Object Models) stored in internal memory created via xmlTree, but methods for XMLNode and XMLOutputStream objects allow it to be generic for different representations of the XML tree.

Usage

saveXML(doc, file=NULL, compression=0, indent=TRUE, prefix = '<?xml version="1.0"?>\n',
        doctype = NULL, encoding = "")
saveXML.XMLInternalDocument(doc, file=NULL, compression=0, indent=TRUE, prefix = '<?xml version="1.0"?>\n',
                            doctype = NULL, encoding = "")
saveXML.XMLInternalDOM(doc, file=NULL, compression=0, indent=TRUE, prefix = '<?xml version="1.0"?>\n',
                       doctype = NULL, encoding = "")
saveXML.XMLNode(doc, file=NULL, compression=0, indent=TRUE, prefix = '<?xml version="1.0"?>\n',
                 doctype = NULL, encoding = "")
saveXML.XMLOutputStream(doc, file=NULL, compression=0, indent=TRUE, prefix = '<?xml version="1.0"?>\n',
                         doctype = NULL, encoding = "")

Arguments

doc | the document object representing the XML document.
file | the name of the file to which the contents of the XML nodes will be serialized.
compression | an integer value between 0 and 9 indicating the level of compression to use when saving the file. Higher values indicate increased compression and hence smaller files at the expense of computational time to do the compression and decompression.
indent | a logical value indicating whether to indent the nested nodes when serializing to the stream.
prefix | a string that is written to the stream/connection before the XML is output. If this is NULL, it is ignored. This allows us to put the XML introduction/preamble at the beginning of the document while allowing it to be omitted when we are outputting multiple "documents" within a single stream.
doctype | an object identifying the elements for the DOCTYPE in the output. This can be a string or an object of class Doctype.
encoding | a string indicating which encoding style to use. This is currently ignored except in the method in Sxslt for saving a document generated by applying an XSL style sheet to an XML document.

Details

One can create an internal XML tree (or DOM) using newXMLDoc and newXMLNode. saveXML allows one to generate a textual representation of that DOM in human-readable and reusable XML format. saveXML is a generic function that allows one to call the rendering operation with either the top-level node of the DOM or of the document object (of class XMLInternalDocument that is used to accumulate the nodes and with which the developer adds nodes.

Value

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.omegahat.org/RSXML

See Also

newXMLDoc newXMLNode xmlOutputBuffer xmlOutputDOM

Examples

con <- xmlOutputDOM()
con$addTag("author", "Duncan Temple Lang")
con$addTag("address",  close=FALSE)
con$addTag("office", "2C-259")
con$addTag("street", "Mountain Avenue.")
con$addTag("phone", close=FALSE)
con$addTag("area", "908", attrs=c(state="NJ"))
con$addTag("number", "582-3217")
con$closeTag() # phone
con$closeTag() # address

saveXML(con$value(), file="out.xml")

# Work with entities

 f = system.file("exampleData", "test1.xml", package = "XML")
 doc = xmlRoot(xmlTreeParse(f))
 outFile = tempfile()
 saveXML(doc, outFile)
 alt = xmlRoot(xmlTreeParse(outFile))
 if(! identical(doc, alt) )
  stop("Problems handling entities!")

 con = textConnection("test1.xml", "w")
 saveXML(doc, con)
 close(con)
 alt = get("test1.xml")
 identical(doc, alt)


Generic Methods for SAX callbacks

Description

This is a collection of generic functions for which one can write methods so that they are called in repsonse to different SAX events. The idea is that one defines methods for different classes of the .state argument and dispatch to different methods based on that argument. The functions represent the different SAX events.

Usage

startElement.SAX(name, atts, .state = NULL)
endElement.SAX(name, .state = NULL)
comment.SAX(content, .state = NULL)
processingInstruction.SAX(target, content, .state = NULL)
text.SAX(content, .state = NULL)
entityDeclaration.SAX(name, base, sysId, publicId, notationName,  .state = NULL)
.InitSAXMethods(where = "package:XML")

Arguments

name | the name of the XML element or entity being declared
atts |
content | the value/string in the processing instruction or comment
target | the target of the processing instruction, e.g. the R in <?R....>
base | x
sysId | the system identifier for this entity
publicId | the public identifier for the entity
notationName | name of the notation specification
.state | the state object on which the user-defined methods should dispatch.
where | the package in which the class and method definitions should be defined. This is almost always unspecified.

Value

Each method should return the (potentially modified) state value.

Note

This no longer requires the Expat XML parser to be installed. Instead, we use libxml's SAX parser.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org

See Also

xmlEventParse

Examples
[Package XML version 1.6-3 Index]


A virtual base class defining methods for SAX parsing

Description

This is a degenerate virtual class which others are expected to sub-class so as to define when they want to use S4 methods as handler functions for SAX-based XML parsing. The idea is that one can pass both i) a collection of handlers to xmlEventParse which are simply the generic functions for the different SAX actions, and ii) a suitable object to maintain state across the different SAX calls. This is used to perform the method dispatching to get the appropriate behavior for the action. Each of these methods is expected to return the updated state object and the SAX parser will pass this in the next callback.

We define this class here so that we can provide default methods for each of the different handler actions. This allows other programmers to define new classes to maintain state that are sub-class of SAXState and then they do not have to implement methods for each of the different handlers.

Objects from the Class

A virtual Class: No objects may be created from it.

Methods

comment.SAX
signature(content = "ANY", .state = "SAXState"): ...
endElement.SAX
signature(name = "ANY", .state = "SAXState"): ...
entityDeclaration.SAX
signature(name = "ANY", base = "ANY", sysId = "ANY", publicId = "ANY", notationName = "ANY", .state = "SAXState"): ...
processingInstruction.SAX
signature(target = "ANY", content = "ANY", .state = "SAXState"): ...
startElement.SAX
signature(name = "ANY", atts = "ANY", .state = "SAXState"): ...
text.SAX
signature(content = "ANY", .state = "SAXState"): ...

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org

See Also

xmlEventParse

Examples
[Package XML version 1.6-3 Index]


Determines which native XML parsers are being used.

Description

Use of the Gnome libxml and Expat parsers is supported in this R/S XML package, but both need not be used when compiling the package. These functions determine whether each is available in the underlying native code.

Usage

supportsExpat()
supportsLibxml()

Details

One might to use different parsers to test validity of a document in different ways and to get different error messages. Additionally, one parser may be more efficient than the other. These methods allow one to write code in such a way that one parser is preferred and is used if it is available, but the other is used if the first is not available.

Value

Returns TRUE if the corresponding library has been linked into the package.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlEventParse

Examples

     # use Expat if possible, otherwise libxml
  fileName <- system.file("exampleData", "mtcars.xml", package="XML")
  xmlEventParse(fileName, useExpat = supportsLibxml())


Creates string representation of XML node

Description

This creates a string from a hierarchical XML node and its children just as it prints on the console or one might see it in a document.

Usage

toString.XMLNode(x, ...)

Arguments

x | an object of class XMLNode.
... | currently ignored

Details

This uses a textConnection object using the name .tempXMLOutput. Since this is global, it will overwrite any existing object of that name! As a result, this function cannot be used recursively in its present form.

Value

A character vector with one element, that being the string corresponding to the XML node's contents.

Note

This requires the Expat XML parser to be installed.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml

See Also

xmlNode xmlTreeParse

Examples

 x <- xmlRoot(xmlTreeParse(system.file("exampleData", "gnumeric.xml",
package = "XML")))

 toString(x)


Applies a function to each of the children of an XMLNode

Description

These methods are simple wrappers for the lapply and sapply functions. They operate on the sub-nodes of the XML node, and not on the fields of the node object itself.

Usage

xmlApply(X, FUN, ...)
xmlApply.XMLNode(X, FUN, ...)
xmlApply.XMLDocument(X, FUN, ...)
xmlApply.XMLDocumentContent(X, FUN, ...)
xmlSApply(X, FUN, ...)
xmlSApply.XMLNode(X, FUN, ...)
xmlSApply.XMLDocument(X, FUN, ...)

Arguments

X | the XMLNode on whose children the regular apply or sapply is to be performed
FUN | the function to apply to each child node. This is passed directly to the relevant apply function.
... | additional arguments to be given to each invocation of FUN. This is passed directly to the relevant apply function.

Value

The result is that obtained from calling the apply or sapply on xmlChildren(x).

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlChildren xmlRoot [.XMLNode sapply lapply

Examples

 doc <- xmlTreeParse(system.file("exampleData", "mtcars.xml", package="XML"))
 r <- xmlRoot(doc)
 xmlSApply(r[[2]], xmlName)

 xmlApply(r[[2]], xmlAttrs)

 xmlSApply(r[[2]], xmlSize)


The type of an XML attribute for element from the DTD

Description

This examines the definition of the attribute, usually returned by parsing the DTD with parseDTD and determines its type from the possible values: Fixed, string data, implied, required, an identifier, an identifier reference, a list of identifier references, an entity, a list of entities, a name, a list of names, an element of enumerated set, a notation entity.

Usage

xmlAttributeType(def, defaultType=FALSE)

Arguments

def | the attribute definition object, usually retrieved from the DTD via parseDTD.
defaultType | whether to return the default value if this attribute is defined as being a value from an enumerated set.

Value

A string identifying the type for the sspecified attributed.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.omegahat.org/RSXML

See Also

parseDTD

Examples
[Package XML version 1.6-3 Index]


Get the list of attributes of an XML node.

Description

This returns a named character vector giving the name-value pairs of attributes of an XMLNode object which is part of an XML document.

Usage

 xmlAttrs(node, ...)

Arguments

node | The XMLNode object whose attributes are to be extracted.
... | additional arguments for the specific methods.

Value

A named character vector, where the names are the attribute names and the elements are the corresponding values. This corresponds to the (attr<i>, "value<i>") pairs in the XML tag <tag attr1="value1" attr2="value2"

Author(s)

Duncan Temple Lang

References

http://www.w3.org

See Also

xmlChildren, xmlSize, xmlName

Examples

 fileName <- system.file("exampleData", "mtcars.xml", package="XML")
 doc <- xmlTreeParse(fileName)

 xmlAttrs(doc$doc$children[["dataset"]])

 xmlAttrs(doc$doc$children[["dataset"]][["variables"]])


Gets the sub-nodes within an XMLNode object.

Description

These functions provide access to the children of the given XML node. The simple accessor returns a list of child XMLNode objects within an XMLNode object.

The assignment operator (xmlChildren<-) sets the children of the node to the given value and returns the updated/modified node. No checking is currently done on the type and values of the right hand side. This allows the children of the node to be arbitrary R objects. This can be useful but means that one cannot rely on any structure in a node being present..

Usage

xmlChildren(x)

Arguments

x an object of class XMLNode.

Value

A list whose elements are sub-nodes of the user-specified XMLNode. These are also of class XMLNode.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML

See Also

xmlChildren,xmlSize, xmlTreeParse

Examples

  fileName <- system.file("exampleData", "mtcars.xml", package="XML")
  doc <- xmlTreeParse(fileName)
  names(xmlChildren(doc$doc$children[["dataset"]]))


Checks if an entity is defined within a DTD.

Description

A DTD contains entity and element definitions. These functions test whether a DTD contains a definition for a particular named element or entity.

Usage

xmlContainsEntity(name, dtd)
xmlContainsElement(name, dtd)

Arguments

name | The name of the element or entity being queried.
dtd | The DTD in which to search for the entry.

Details

See parseDTD for more information about DTDs, entities and elements.

Value

A logical value indicating whether the entry was found in the appropriate list of entitiy or element definitions.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

parseDTD, dtdEntity, dtdElement,

Examples

 dtdFile <- system.file("exampleData", "foo.dtd", package="XML")
 foo.dtd <- parseDTD(dtdFile)

  # Look for entities.
 xmlContainsEntity("foo", foo.dtd)
 xmlContainsEntity("bar", foo.dtd)

  # Now look for an element
 xmlContainsElement("record", foo.dtd)


Apply function to nodes in an XML tree/DOM.

Description

This recursively applies the specified function to each node in an XML tree, creating a new tree, parallel to the original input tree. Each element in the new tree is the return value obtained from invoking the specified function on the corresponding element of the original tree. The order in which the function is recursively applied is "bottom-up". In other words, function is first applied to each of the children nodes first and then to the parent node containing the newly computed results for the children.

Usage

xmlDOMApply(dom, func)

Arguments

dom | a node in the XML tree or DOM on which to recursively apply the given function. This should not be the XMLDocument itself returned from xmlTreeParse but an object of class XMLNode. This is typically obtained by calling xmlRoot on the return value from xmlTreeParse.
func | the function to be applied to each node in the XML tree. This is passed the node object for the and the return value is inserted into the new tree that is to be returned in the corresponding position as the node being processed. If the return value is NULL, this node is dropped from the tree.

Details

This is a native (C code) implementation that understands the structure of an XML DOM returned from xmlTreeParse and iterates over the nodes in that tree.

Value

A tree that parallels the structure in the dom object passed to it.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlTreeParse

Examples

 dom <- xmlTreeParse(system.file("exampleData","mtcars.xml", package="XML"))
 tagNames <- function() {
    tags <- character(0)
    add <- function(x) {
      if(inherits(x, "XMLNode")) {
        if(is.na(match(xmlName(x), tags)))
           tags <<- c(tags, xmlName(x))
      }

      NULL
    }

    return(list(add=add, tagNames = function() {return(tags)}))
 }

 h <- tagNames()
 xmlDOMApply(xmlRoot(dom), h$add)
 h$tagNames()


Retrieve the children of an XML node with a specific tag name

Description

This returns a list of the children or sub-elements of an XML node whose tag name matches the one specified by the user.

Usage

xmlElementsByTagName(el, name, recursive = FALSE)

Arguments

el | the node whose matching children are to be retrieved.
name | a string giving the name of the tag to match in each of el's children.
recursive | a logical value. If this is FALSE, the default, only the direct child nodes are searched. Alternatively, if this is TRUE, all sub-nodes at all levels are searched. In other words, we find all descendants of the node el and return a list with the nodes having the given name. The relationship between the nodes in the resulting list cannot be determined. This is a set of nodes. See the note.

Details

This does a simple matching of names and subsets the XML node's children list. If recursive is TRUE, then the function is applied recursively to the children of the given node and so on.

Value

A list containing those child nodes of el whose tag name matches that specified by the user.

Note

The addition of the recursive argument makes this function behave like the getElementsByTagName in other language APIs such as Java, C#. However, one should be careful to understand that in those languages, one would get back a set of node objects. These nodes have references to their parents and children. Therefore one can navigate the tree from each node, find its relations, etc. In the current version of this package (and for the forseeable future), the node set is a “copy” of the nodes in the original tree. And these have no facilities for finding their siblings or parent. Additionally, one can consume a large amount of memory by taking a copy of numerous large nodes using this facility. If one does not modify the nodes, the extra memory may be small. But modifying them means that the contents will be copied.

Alternative implementations of the tree, e.g. using unique identifiers for nodes or via internal data structures from libxml can allow us to implement this function with different semantics, more similar to the other APIs.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.omegahat.org/RSXML,

See Also

xmlChildren xmlTreeParse

Examples

## Not run:
 doc <- xmlTreeParse("http://www.omegahat.org/Scripts/Data/mtcars.xml")
 xmlElementsByTagName(doc$children[[1]], "variable")
## End(Not run)

 doc <- xmlTreeParse(system.file("exampleData", "mtcars.xml", package="XML"))
 xmlElementsByTagName(xmlRoot(doc)[[1]], "variable")


Default handlers for the SAX-style event XML parser

Description

This is a function that returns a closure instance containing the default handlers for use with xmlEventParse for parsing XML documents via the SAX-style parsing.

Usage

xmlEventHandler()

Details

These handlers simply build up the DOM tree and thus perform the same job as xmlTreeParse. It is here more as an example, reference and a base that users can extend.

Value

The return value is a list of functions which are used as callbacks by the internal XML parser when it encounters certain XML elements/structures. These include items such as the start of an element, end of an element, processing instruction, text node, comment, entity references and definitions, etc.

startElement
endElement
processingInstruction
text
comment
externalEntity
entityDeclaration
cdata
dom

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlEventParse xmlTreeParse

Examples

 xmlEventParse(system.file("exampleData", "mtcars.xml", package="XML"),
               handlers=xmlEventHandler())


XML Event/Callback element-wise Parser

Description

This is the event-driven or SAX (Simple API for XML) style parser which process XML without building the tree but rather identifies tokens in the stream of characters and passes them to handlers which can make sense of them in context. This reads and processes the contents of an XML file or string by invoking user-level functions associated with different components of the XML tree. These components include the beginning and end of XML elements, e.g <myTag x="1"> and </myTag> respectively, comments, CDATA (escaped character data), entities, processing instructions, etc. This allows the caller to create the appropriate data structure from the XML document contents rather than the default tree (see xmlTreeParse) and so avoids having the entire document in memory. This is important for large documents and where we would end up with essentially 2 copies of the data in memory at once, i.e the tree and the R data structure containing the information taken from the tree. When dealing with classes of XML documents whose instances could be large, this approach is desirable but a little more cumbersome to program than the standard DOM (Document Object Model) approach provided by XMLTreeParse.

Note that xmlTreeParse does allow a hybrid style of processing that allows us to apply handlers to nodes in the tree as they are being converted to R objects. This is a style of event-driven or asynchronous calling

In addition to the generic token event handlers such as "begin an XML element" (the startElement handler), one can also provide handler functions for specific tags/elements such as <myTag> with handler elements with the same name as the XML element of interest, i.e. "myTag" = function(x, attrs).

Usage

xmlEventParse(file, handlers=xmlEventHandler(), ignoreBlanks = FALSE, addContext=TRUE,
               useTagName=TRUE, asText = FALSE, trim=TRUE, useExpat=FALSE, isURL = FALSE,
                state = NULL, replaceEntities = TRUE, validate = FALSE,
                 saxVersion = 1, branches = NULL)

Arguments

file the source of the XML content. This can be a string giving the name of a file or remote URL, the XML itself, a connection object, or a function. If this is a string, and asText is TRUE, the value is the XML content. This allows one to read the content separately from parsing without having to write it to a file. If asText is FALSE and a string is passed for file, this is taken as the name of a file or remote URI. If one is using the libxml parser (i.e. not expat), this can be a URI accessed via HTTP or FTP or a compressed local file. If it is the name of a local file, it can include ~, environment variables, etc. which will be expanded by R. (Note this is not the case in S-Plus, as far as I know.)
If a connection is given, the parser incrementally reads one line at a time by calling the function readLines with the connection as the first argument (and 1 as the number of lines to read). The parser calls this function each time it needs more input.
If invoking the readLines function to get each line is excessively slow or is inappropriate, one can provide a function as the value of fileName. Again, when the XML parser needs more content to process, it invokes this function to get a string. This function is called with a single argument, the maximum size of the string that can be returned. The function is responsible for accessing the correct connection(s), etc. which is typically done via lexical scoping/environments. This mechanism allows the user to control how the XML content is retrieved in very general ways. For example, one might read from a set of files, starting one when the contents of the previous file have been consumed. This allows for the use of hybrid connection objects.
Support for connections and functions in this form is only provided if one is using libxml2 and not libxml version 1.
handlers | a closure object that contains functions which will be invoked as the XML components in the document are encountered by the parser. The standard functions are startElement(), endElement() comment(), externalEntity(), entityDeclaration(), processingInstruction(), text(), cdata(), startDocument(), and endDocument().
ignoreBlanks | a logical value indicating whether text elements made up entirely of white space should be included in the resulting `tree'.
addContext | logical value indicating whether the callback functions in `handlers' should be invoked with contextual information about the parser and the position in the tree, such as node depth, path indices for the node relative the root, etc. If this is True, each callback function should support ....
useTagName | logical value indicating whether the callback mechanism should look for a function matching the tag name in the startElement and endElement events, before calling the default handler functions. This allows the caller to handle different element types for a particular DTD with their own functions directly, rather than performing a second dispatch in startElement().
asText | logical value indicating that the first argument, `file', should be treated as the XML text to parse, not the name of a file. This allows the contents of documents to be retrieved from different sources (e.g. HTTP servers, XML-RPC, etc.) and still use this parser.
trim | whether to strip white space from the beginning and end of text strings.
useExpat | a logical value indicating whether to use the expat SAX parser, or to default to the libxml. If this is TRUE, the library must have been compiled with support for expat. See supportsExpat.
isURL | indicates whether the file argument refers to a URL (accessible via ftp or http) or a regular file on the system. If asText is TRUE, this should not be specified.
state | an optional S object that is passed to the callbacks and can be modified to communicate state between the callbacks. If this is given, the callbacks should accept an argument named .state and it should return an object that will be used as the updated value of this state object. The new value can be any S object and will be passed to the next callback where again it will be updated by that functions return value, and so on. If this not specified in the call to xmlEventParse, no .state argument is passed to the callbacks. This makes the interface compatible with previous releases.
replaceEntities | logical value indicating whether to substitute entity references with their text directly. This should be left as False. The text still appears as the value of the node, but there is more information about its source, allowing the parse to be reversed with full reference information.
saxVersion | an integer value which should be either 1 or 2. This specifies which SAX interface to use in the C code. The essential difference is the number of arguments passed to the startElement handler function(s). In addition to the name of the element and the named-attributes vector, two additional arguments are provided. The first identifies the namespace of the element. This is a named character vector of length 1, with the value being the URI of the namespace and the name being the prefix that identifies that namespace within the document. For example, xmlns:r="http://www.r-project.org" would be passed as c(r = "http://www.r-project.org"). If there is no prefix because the namespace is being used as the default, the result of calling names on the string is "". The fourth argument gives the collection of all the namespaces defined within this element. Again, this is a named character vector.
validate | Currently, this has no effect as the libxml2 parser uses a document structure to do validation. a logical indicating whether to use a validating parser or not, or in other words check the contents against the DTD specification. If this is true, warning messages will be displayed about errors in the DTD and/or document, but the parsing will proceed except for the presence of terminal errors.
branches a named list of functions. Each element identifies an XML element name. If an XML element of that name is encountered in the SAX stream, the stream is processed until the end of that element and an internal node (see xmlTreeParse and its useInternalNodes parameter) is created. The function in our branches list corresponding to this XML element is then invoked with the (internal) node as the only argument. This allows one to use the DOM model on a sub-tree of the entire document and thus use both SAX and DOM together to get the efficiency of SAX and the simpler programming model of DOM.
Note that the branches mechanism works top-down and does not work for nested tags. If one specifies an element name in the branches argument, e.g. myNode, and there is a nested myNode instance within a branch, the branches handler will not be called for that nested instance. If there is an instance where this is problematic, please contact the maintainer of this package.

Details

This is now implemented using the libxml parser. Originally, this was implemented via the Expat XML parser by Jim Clark (http://www.jclark.com).

Value

The return value is the `handlers' argument. It is assumed that this is a closure and that the callback functions have manipulated variables local to it and that the caller knows how to extract this.

Note

The libxml parser can read URLs via http or ftp. It does not require the support of textbf{wget} as used in other parts of R, but uses its own facilities to connect to remote servers.

The idea for the hybrid SAX/DOM mode where we consume tokens in the stream to create an entire node for a sub-tree of the document was first suggested to me by Seth Falcon at the Fred Hutchinson Cancer Research Center. It is similar to the XML::Twig module in Perl by Michel Rodriguez.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml

See Also

xmlTreeParse

Examples

 fileName <- system.file("exampleData", "mtcars.xml", package="XML")

   # Print the name of each XML tag encountered at the beginning of each
   # tag.
   # Uses the libxml SAX parser.
 xmlEventParse(fileName,
                list(startElement=function(name, attrs){
                                    cat(name,"\n")
                                  }),
                useTagName=FALSE, addContext = FALSE)

## Not run:
  # Parse the text rather than a file or URL by reading the URL's contents
  # and making it a single string. Then call xmlEventParse
xmlURL <- "http://www.omegahat.org/Scripts/Data/mtcars.xml"
xmlText <- paste(scan(xmlURL, what="",sep="\n"),"\n",collapse="\n")
xmlEventParse(xmlText, asText=TRUE)
## End(Not run)

    # Using a state object to share mutable data across callbacks
f <- system.file("exampleData", "gnumeric.xml", package = "XML")
zz <- xmlEventParse(f,
                    handlers = list(startElement=function(name, atts, .state) {
                                                     .state = .state + 1
                                                     print(.state)
                                                     .state
                                                 }), state = 0)
print(zz)

    # Illustrate the startDocument and endDocument handlers.
xmlEventParse(fileName,
               handlers = list(startDocument = function() {
                                                 cat("Starting document\n")
                                               },
                               endDocument = function() {
                                                 cat("ending document\n")
                                             }),
               saxVersion = 2)

if(libxmlVersion()$major >= 2) {

 startElement = function(x, ...) cat(x, "\n")

 xmlEventParse(file(f), handlers = list(startElement = startElement))

 # Parse with a function providing the input as needed.
 xmlConnection =
  function(con) {

   if(is.character(con))
     con = file(con, "r")

   if(isOpen(con, "r"))
     open(con, "r")

   function(len) {

     if(len < 0) {
        close(con)
        return(character(0))
     }

      x = character(0)
      tmp = ""
    while(length(tmp) > 0 && nchar(tmp) == 0) {
      tmp = readLines(con, 1)
      if(length(tmp) == 0)
        break
      if(nchar(tmp) == 0)
        x = append(x, "\n")
      else
        x = tmp
    }
    if(length(tmp) == 0)
      return(tmp)

    x = paste(x, collapse="")

    x
  }
 }

 ff = xmlConnection(f)
 xmlEventParse(ff, handlers = list(startElement = startElement))

  # Parse from a connection. Each time the parser needs more input, it
  # calls readLines(<con>, 1)
 xmlEventParse(file(f),  handlers = list(startElement = startElement))

  # using SAX 2
 h = list(startElement = function(name, attrs, namespace, allNamespaces){
                                 cat("Starting", name,"\n")
                                 if(length(attrs))
                                     print(attrs)
                                 print(namespace)
                                 print(allNamespaces)
                         },
          endElement = function(name, uri) {
                          cat("Finishing", name, "\n")
            })
 xmlEventParse(system.file("exampleData", "namespaces.xml", package="XML"), handlers = h, saxVersion = 2)

 # This example is not very realistic but illustrates how to use the
 # branches argument. It forces the creation of complete nodes for
 # elements named <b> and extracts the id attribute.
 # This could be done directly on the startElement, but this just
 # illustrates the mechanism.
 filename = system.file("exampleData", "branch.xml", package="XML")
 b.counter = function() {
                nodes <- character()
                f = function(node) { nodes <<- c(nodes, xmlGetAttr(node, "id"))}
                list(b = f, nodes = function() nodes)
             }

  b = b.counter()
  invisible(xmlEventParse(filename, branches = b["b"]))
  b$nodes()

  filename = system.file("exampleData", "branch.xml", package="XML")

  invisible(xmlEventParse(filename, branches = list(b = function(node) {print(names(node))})))
  invisible(xmlEventParse(filename, branches = list(b = function(node) {print(xmlName(xmlChildren(node)[[1]]))})))
}


Constructors for trees stored as flat list of nodes with information about parents and children.

Description

These (and related internal) functions allow us to represent trees as a simple, non-hierarchical collection of nodes along with corresponding tables that identify the parent and child relationships. This is different from representing a tree as a list of lists of lists ... in which each node has a list of its own children. In a functional language like R, it is not possible then for the children to be able to identify their parents.

We use an environment to represent these flat trees. Since these are mutable without requiring the change to be reassigned, we can modify a part of the tree locally without having to reassign the top-level object.

We can use either a list (with names) to store the nodes or a hash table/associative array that uses names. There is a non-trivial performance difference.

Usage

xmlHashTree(nodes = list(), parents = character(), children = list(),
             env = new.env(TRUE))
xmlFlatListTree(nodes = list(), parents = character(), children = list(), env = new.env(), n = 200)

Arguments

nodes | a collection of existing nodes that are to be added to the tree. These are used to initialize the tree. If this is specified, you must also specify children and parents.
parents | the parent relationships for the nodes given by nodes.
children | the children relationships for the nodes given by nodes.
env | an environment in which the information for the tree will be stored. This is essentially the tree object as it allows us to modify parts of the tree without having to reassign the top-level object. Unlike most R data types, environments are mutable.
n | for xmlFlatListTree, this is used as the default size to allocate for the list containing the nodes

Details

Value

An object of class XMLFlatTree which is specialized to XMLFlatListTree by the xmlFlatListTree function and XMLHashTree by the xmlHashTree function. Both objects are simply the environment which contains information about the tree elements and functions to access this information.
An xmlHashTree object has an accessor method via $ for accessing individual nodes within the tree. One can use the node name/identifier in an expression such as tt$myNode to obtain the element. The name of a node is either its XML node name or if that is already present in the tree, a machine generated name.
One can find the names of all the nodes using the objects function since these trees are regular environments in R. Using the all = TRUE argument, one can also find the “hidden” elements that make define the tree's structure. These are .children and .parents. The former is an (hashed) environment. Each element is identified by the node in the tree by the node's identifier (corresponding to the name of the node in the tree's environment). The value of that element is simply a character vector giving the identifiers of all of the children of that node.
The .parents element is also an environemnt. Each element in this gives the pair of node and parent identifiers with the parent identifier being the value of the variable in the environment. In other words, we look up the parent of a node named 'kid' by retrieving the value of the variable 'kid' in the .parents environment of this hash tree.
The function .addNode is used to insert a new node into the tree.
The structure of this tree allows one to easily travers all nodes, navigate up the tree from a node via its parent. Certain tasks are more complex as the hierarchy is not implicit within a node.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML

See Also

xmlTreeParse xmlTree xmlOutputBuffer xmlOutputDOM

Examples

 f = system.file("exampleData", "dataframe.xml", package = "XML")
 tr  = xmlHashTree()
 xmlTreeParse(f, handlers = tr[[".addNode"]])

 tr # print the tree on the screen

  # Get the two child nodes of the dataframe node.
 xmlChildren(tr$dataframe)

  # Find the names of all the nodes.
 objects(tr)
  # Which nodes have children
 objects(tr$.children)

  # Which nodes are leaves, i.e. do not have children
 setdiff(objects(tr), objects(tr$.children))

  # find the class of each of these leaf nodes.
 sapply(setdiff(objects(tr), objects(tr$.children)),
         function(id) class(tr[[id]]))

  # distribution of number of children
 sapply(tr$.children, length)

  # Get the first A node
 tr$A

  # Get is parent node.
 xmlParent(tr$A)


Get the value of an attribute in an XML node

Description

This is a convenience function that retrieves the value of a named attribute in an XML node, taking care of checking for its existence. It also allows the caller to provide a default value to use as the return value if the attribute is not present.

Usage

xmlGetAttr(node, name, default = NULL, converter = NULL)

Arguments

node | the XML node
name | the name of the attribute
default | a value to use as the default return if the attribute is not present in the XML node.
converter | an optional function which if supplied is invoked with the attribute value and the value returned. This can be used to convert the string to an arbitrary value which is useful if it is, for example, a number. This is only called if the attribute exists within the node. In other words, it is not applied to the default value.

Details

This just checks that the attribute list is non-NULL and that there is an element with the specified name.

Value

If the attribute is present, the return value is a string which is the value of the attribute. Otherwise, the value of default is returned.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlAttrs

Examples

 node <- xmlNode("foo", attrs=c(a="1", b="my name"))

 xmlGetAttr(node, "a")
 xmlGetAttr(node, "doesn't exist", "My own default value")

 xmlGetAttr(node, "b", "Just in case")


Example XML Event Parser Handler Functions

Description

A closure containing simple functions for the different types of events potentially called by the xmlEventParse, and some tag-specific functions to illustrate how one can add functions for specific DTDs and XML element types. Contains a local list which can be mutated by invocations of the closure's function.

Usage

xmlHandler()

Value

List containing the functions enumerated in the closure definition along with the list.

Note

This is just an example.

Author(s)

Duncan Temple Lang

See Also

xmlEventParse, xmlTreeParse

Examples

## Not run:
xmlURL <- "http://www.omegahat.org/Scripts/Data/mtcars.xml"
xmlText <- paste(scan(xmlURL, what="", sep="\n"),"\n",collapse="\n")
## End(Not run)

xmlURL <- system.file("exampleData", "mtcars.xml", package="XML")
xmlText <- paste(readLines(xmlURL), "\n", collapse="")
xmlEventParse(xmlText, handlers = NULL, asText=TRUE)
xmlEventParse(xmlText, xmlHandler(), useTagName=TRUE, asText=TRUE)


Class to represent reference to C-level data structure for an XML document

Description

This class is used to provide a handle/reference to a C-level data structure that contains the information from parsing parsing XML content. This leaves the nodes in the DOM or tree as C-level nodes rather than converting them to explicit R XMLNode objects. One can then operate on this tree in much the same way as one can the XMLNode representations, but we a) avoid copying the nodes to R, and b) can navigate the tree both down and up using xmlParent giving greater flexibility. Most importantly, one can use an XMLInternalDocument class object with an XPath expression to easily and relatively efficiently find nodes within a document that satisfy some criterion. See getNodeSet.

Objects from the Class

Objects of this type are created via xmlTreeParse and htmlTreeParse with the argument useInternalNodes given as TRUE.

Extends

Class oldClass, directly.

Methods

References

XPath

See Also

xmlTreeParse htmlTreeParse getNodeSet

Examples

 f = system.file("exampleData", "mtcars.xml", package="XML")
 doc = xmlTreeParse(f, useInternalNodes = TRUE)
 getNodeSet(doc, "//variables[@count]")
 getNodeSet(doc, "//record")

 getNodeSet(doc, "//record[@id='Mazda RX4']")


Extraces the tag name of an XMLNode object.

Description

Each XMLNode object has a tag name introduced in the <name ...> entry in an XML document. This function returns that name.

Usage

xmlName(node, full = FALSE)

Arguments

node | The XMLNode object whose tag name is being requested.
full | a logical value indicating whether to prepend the namespace prefix, if there is one, or return just the name of the XML element/node. TRUE means prepend the prefix.

Value

A character vector of length textit{1} which is the node$name entry.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlChildren, xmlAttrs, xmlTreeParse

Examples

 fileName <- system.file("exampleData", "test.xml", package="XML")
 doc <- xmlTreeParse(fileName)
 xmlName(xmlRoot(doc)[[1]])


Retrieve the namespace value of an XML node.

Description

Each XML node has a namespace identifier which is a string indicating in which DTD (Document Type Definition) the definition of that element can be found. This avoids the problem of having different document definitions using the same names for XML elements that have different meaning. To resolve the name space, i.e. i.e. find out to where the identifier points, one can use the expression xmlNamespace(xmlRoot(doc)).

The class of the result is is an S3-style object of class XMLNamespace.

Usage

xmlNamespace(x)

Arguments

x the object whose namespace is to be computed

Value

For non-root nodes, this returns a string giving the identifier of the name space for this node. For the root node, this returns a list with $3$ elements:

id | the identifier by which other nodes refer to this namespace.
uri | the URI or location that defines this namespace.
local | ? (can't remember off-hand).

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlName xmlChildren xmlAttrs xmlValue

Examples

  doc <- xmlTreeParse(system.file("exampleData", "job.xml", package="XML"))
  xmlNamespace(xmlRoot(doc))
  xmlNamespace(xmlRoot(doc)[[1]][[1]])

  node <- xmlNode("arg", xmlNode("name", "foo"), namespace="R")
  xmlNamespace(node)


Get definitions of any namespaces defined in this XML node

Description

If the given node has any namespace definitions declared within it, i.e. of the form xmlns:myNamespace="http://www.myNS.org", this function provides access to these definitions. While they appear in the XML node in the document as attributes, they are treated differently by the parser and so do not show up in the nodes attributes via xmlAttrs.

Usage

xmlNamespaceDefinitions(x, addNames = TRUE)

Arguments

x | the XMLNode object in which to find any namespace definitions
addNames | a logical indicating whether to compute the names for the elements in the resulting list. The names are convenient, but one can avoid the (very small) overhead of computing these with this parameter.

Details

Value

A list with as many elements as there are namespace definitions. Each element is an object of class XMLNameSpace, containing fields giving the local identifier, the associated defining URI and a logical value indicating whether the definition is local to this node.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML

See Also

xmlTreeParse xmlAttrs xmlGetAttr

Examples

  f = system.file("exampleData", "longitudinalData.xml", package = "XML")
  n = xmlRoot(xmlTreeParse(f))
  xmlNamespaceDefinitions(n)


Create an XML node

Description

These functions allow one to create XML nodes as are created in C code when reading XML documents. Trees of XML nodes can be constructed and integrated with other trees generated manually or with via the parser.

Usage

xmlNode(name, ..., attrs=NULL, namespace="")
xmlTextNode(value, namespace="", entities = XMLEntities)
xmlPINode(sys, value, namespace="")
xmlCDataNode(...)
xmlCommentNode(text)

Arguments

name | The tag or element name of the XML node. This is what appears in the elements as <name> .. </name>
... | The children nodes of this XML node. These can be objects of class XMLNode or arbitrary values that will be converted to a string to form an XMLTextNode object.
attrs | A named character vector giving the name, value pairs of attributes for this XML node.
value | This is the text that is to be used when forming an XMLTextNode.
namespace | The XML namespace identifier for this node.
sys | the name of the system for which the processing instruction is targeted. This is the value that appears in the <?sys value?>
text | character string giving the contents of the comment.
entities | a character vector giving the mapping from special characters to their entity equivalent. This provides the character-expanded entity pairings of 'character = entity' , e.g. '<' = "lt" which are used to make the content valid XML so that it can be used within a text node. The text searched sequentially for instances of each character in the names and each instance is replaced with the corresponding '&entity;'

Value

An object of class XMLNode. In the case of xmlTextNode, this also inherits from XMLTextNode. The fields or slots that objects of these classes have include name, attributes, children and namespace. However, one should the accessor functions xmlName, xmlAttrs, xmlChildren and xmlNamespace

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlTreeParse asXMLNode

Examples

a <- xmlNode("arg", attrs = c(default="T"),
               xmlNode("name", "foo"), xmlNode("defaultValue","1:10"))


Classes to describe an XML node object.

Description

These classes are intended to represent an XML node, either directly in S or a reference to an internal libxml node. Such nodes respond to queries about their name, attributes, namespaces and children. These are old-style, S3 classes at present.

Slots

Methods

No methods defined with class "XMLNode" in the signature.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org

See Also

xmlTreeParse xmlTree

Examples
[Package XML version 1.6-3 Index]


XML output streams

Description

These two functions provide different ways to construct XML documents incrementally. They provide a single, common interface for adding and closing tags, and inserting nodes. The buffer version stores the XML representation as a string. The DOM version builds the tree of XML node objects.

Usage

xmlOutputBuffer(dtd=NULL, nameSpace="", buf=NULL,
                 nsURI=NULL, header="<?xml version=\"1.0\"?>")

xmlOutputDOM(tag="doc", attrs = NULL, dtd=NULL,
                 nameSpace=NULL, nsURI=character(0))

Arguments

dtd | a DTD object (see parseDTD and xmlTreeParse) which contains specifications about what elements are valid within other elements and what attributes are supported by different elements. This can be used to validate the document as it is being constructed incrementally.
attrs | attributes for the top-level node, in the form of a named vector or list.
nameSpace | the default namespace identifier to be used when an element is created without an explicit namespace. This provides a convenient way to specify the default name space that appers in tags throughout the resulting document.
buf | a connection object or a string into which the XML content is written. This is currently a simplistic implementation since we will use the OOP-style classes from the Omegahat projects in the future.
nsURI | the URI or value for the name space which is used when declaring the namespace. For xmlOuputDOM, this is a named character vector with each element giving the name space identifier and the corresponding URI, \ e.g c(shelp = "http://www.omegahat.org/XML/SHelp")
header | if non-NULL, this is immediately written to the output stream allowing one to control the initial section of the XML document.
tag | the name of the top-level node/element in the DOM being created.

Details

These functions create a closure instance which provides methods or functions that operate on shared data used to represent the contents of the XML document being created and the current state of that creation.

Value

Both of these functions return a list of functions which operate on the XML data in a shared environment.

value | get the contents of the XML document as they are currently defined.
addTag | add a new element to the document, specifying its name and attributes. This allows the tag to be left open so that new elements will be added as children of it.
closeTag | close the currently open tag, indicating that new elements will be added, by default, as siblings of this one.
reset | discard the current contents of the document so that we can start over and free the resources (memory) associated with this document.
addNode | insert an complete XMLNode object into the currently active (i.e. open) node.
current | obtain the path or collection of indices to to the currently active/open node from the root node.

Author(s)

Duncan Temple Lang

References

http://www.omegahat.org/RSXML, http://www.w3.org/xml

See Also

xmlNode, xmlTextNode, append.xmlNode

Examples

 con <- xmlOutputDOM()
con$addTag("author", "Duncan Temple Lang")
con$addTag("address",  close=FALSE)
 con$addTag("office", "2C-259")
 con$addTag("street", "Mountain Avenue.")
 con$addTag("phone", close=FALSE)
   con$addTag("area", "908", attrs=c(state="NJ"))
   con$addTag("number", "582-3217")
 con$closeTag() # phone
con$closeTag() # address

con$addTag("section", close=FALSE)
 con$addNode(xmlTextNode("This is some text "))
 con$addTag("a","and a link", attrs=c(href="http://www.omegahat.org"))
 con$addNode(xmlTextNode("and some follow up text"))

 con$addTag("subsection", close=FALSE)
   con$addNode(xmlTextNode("some addtional text "))
   con$addTag("a", attrs=c(href="http://www.omegahat.org"), close=FALSE)
     con$addNode(xmlTextNode("the content of the link"))
   con$closeTag() # a
 con$closeTag() # "subsection"
con$closeTag() # section

 d <- xmlOutputDOM()
 d$addPI("S", "plot(1:10)")
 d$addCData('x <- list(1, a="&");\nx[[2]]')
 d$addComment("A comment")
 print(d$value())
 print(d$value(), indent = FALSE, tagSeparator = "")


Get parent node of XMLInternalNode

Description

This operates on an internal C-level XML node and returns a reference to its parent node within the document tree.

Usage

xmlParent(x)

Arguments

x an object of class XMLInternalNode whose parent is being requested.

Details

This uses the internal libxml structures to access the parent in the DOM tree. This function is generic so that we can add methods for other types of nodes if we so want in the future.

Value

An object of class XMLInternalNode.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML

See Also

xmlChildren xmlTreeParse xmlNode

Examples
[Package XML version 1.6-3 Index]


Get the top-level XML node.

Description

These are a collection of methods for providing easy access to the top-level XMLNode object resulting from parsing an XML document. They simplify accessing this node in the presence of auxillary information such as DTDs, file name and version information that is returned as part of the parsing.

Usage

xmlRoot(x, ...)
xmlRoot.XMLDocumentContent(x, ...)
xmlRoot.XMLInternalDocument(x, ...)
xmlRoot.HTMLDocument(x, ...)

Arguments

x | the object whose root/top-level XML node is to be returned.
... | arguments that are passed by the generic to the different specialized methods of this generic.

Value

An object of class XMLNode.

Note

One cannot obtain the parent or top-level node of an XMLNode object in S. This is different from languages like C, Java, Perl, etc. and is primarily because S does not provide support for references.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlTreeParse [[.XMLNode

Examples

  doc <- xmlTreeParse(system.file("exampleData", "mtcars.xml", package="XML"))
  xmlRoot(doc)


The number of sub-elements within an XML node.

Description

XML elements can contain other, nested sub-elements. This generic function determines the number of such elements within a specified node. It applies to an object of class XMLNode or XMLDocument.

Usage

xmlSize(obj)

Arguments

obj An an object of class XMLNode or XMLDocument.

Value

an integer which is the length of the value from xmlChildren.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlChildren, xmlAttrs, xmlName, xmlTreeParse

Examples

  fileName <- system.file("exampleData", "mtcars.xml", package="XML")
  doc <- xmlTreeParse(fileName)
  xmlSize(doc)
  xmlSize(doc$doc$children[["dataset"]][["variables"]])


Convenience accessors for the children of XMLNode objects.

Description

These provide a simplified syntax for extracting the children of an XML node.

Usage

obj[[i]]
"[.XMLNode"(obj, ..., all = FALSE)
"[[.XMLNode"(obj, ...)
"[[.XMLDocumentContent"(obj, ...)

Arguments

obj | the XML node or the top-level document content in which the children are to be accessed. The XMLDocumentContent is the container for the top-level node that also contains information such as the URI/filename and XML version. This accessor method is merely a convenience to get access to children of the top-level node.
i | index of the child of interest or the name of an XML element of interest. In this latter case, only the first matching element is returned, if any.
... | the identifiers for the children to be retrieved, given as integer indices, names, etc. in the usual format for the generic link{[} and link{[[} operators
all | logical value. When ... is a character vector, a value of TRUE for all means to retrieve all of the nodes with those names rather than just the first one. FALSE gives the usual result of subsetting a list by name which gives just the first element. This allows us to avoid the idiom node[ names(node) == "bob" ] which is complicated when node is the result of an inline computation and instead we use node["bob", all = TRUE].

Value

A list or single element containing the children of the XML node given by obj and identified by ....

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.omegahat.org/RSXML

See Also

xmlAttrs [<-.XMLNode [[<-.XMLNode

Examples

 f = system.file("exampleData", "gnumeric.xml", package = "XML")

 top = xmlRoot(xmlTreeParse(f))

  # Get the first RowInfo element.
 top[["Sheets"]][[1]][["Rows"]][["RowInfo"]]

  # Get a list containing only the first row element
 top[["Sheets"]][[1]][["Rows"]]["RowInfo"]
 top[["Sheets"]][[1]][["Rows"]][1]

  # Get all of the RowInfo elements by position
 top[["Sheets"]][[1]][["Rows"]][1:xmlSize(top[["Sheets"]][[1]][["Rows"]])]

  # But more succinctly and accurately, get all of the RowInfo elements
 top[["Sheets"]][[1]][["Rows"]]["RowInfo", all = TRUE]


An internal, updatable DOM object for building XML trees

xmlTree(XML) R Documentation

An internal updatable DOM object for building XML trees

Description

This is a mutable object (implemented via a closure) for representing an XML tree, in the same spirit as xmlOutputBuffer and xmlOutputDOM but that uses the internal structures of libxml. This can be used to create a DOM that can be constructed in R and exported to another system such as XSLT (http://www.omegahat.org/Sxslt)

Usage

xmlTree(tag, attrs = NULL, dtd=NULL, namespaces=list())

Arguments

tag | the tagname of the top-level element. This is basically ignored!
attrs | attributes for the top-level node, in the form of a named vector or list.
dtd | the name of the external DTD for this document. See newXMLDoc
namespaces | a named character vector with each element giving the name space identifier and the corresponding URI, \ e.g c(shelp = "http://www.omegahat.org/XML/SHelp")

Details

This creates a collection of functions that manipulate a shared state to build and maintain an XML tree in C-level code.

Value

An object of class XMLInternalDOM that extends XMLOutputStream and has the same interface (i.e. ``methods'') as xmlOutputBuffer and xmlOutputDOM. Each object has methods for adding a new XML tag, closing a tag, adding an XML comment, and retrieving the contents of the tree.

addTag | create a new tag at the current position, optionally leaving it as the active open tag to which new nodes will be added as children
closeTag | close the currently active tag making its parent the active element into which new nodes will be added.
addComment | add an XML comment node as a child of the active node in the document.
value | retrieve an object representing the XML tree. See saveXML to serialize the contents of the tree.
add | degenerate method in this context.

Note

This is an early version of this function and I need to iron out some of the minor details.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.xmlsoft.org, http://www.omegahat.org

See Also

saveXML newXMLDoc newXMLNode xmlOutputBuffer xmlOutputDOM

Examples

  tr <- xmlTree("Duncan")
  tr$addTag("name", attrs=c(a=1,b="xyz"), close=FALSE)
    tr$addTag("first", "Larry")
    tr$addTag("last", "User")
  tr$closeTag()
  tr$value()
  cat(saveXML(tr$value()))

  tr <- xmlTree("CDataTest")
  tr$addTag("top", close=FALSE)
  tr$addCData("x <- list(1, a='&');\nx[[2]]")
  tr$addPI("S", "plot(1:10)")
  tr$closeTag()
  cat(saveXML(tr$value()))


XML Parser

Description

Parses an XML or HTML file or string, and generates an R structure representing the XML/HTML tree. Use htmlTreeParse when the content is known to be (potentially malformed) HTML.

Usage

xmlTreeParse(file, ignoreBlanks=TRUE, handlers=NULL, replaceEntities=FALSE,
              asText=FALSE, trim=TRUE, validate=FALSE, getDTD=TRUE,
               isURL=FALSE, asTree = FALSE, addAttributeNamespaces = FALSE,
               useInternalNodes = FALSE, isSchema = FALSE,
               fullNamespaceInfo = FALSE, encoding = character())
htmlTreeParse(file, ignoreBlanks = TRUE, handlers = NULL,
               replaceEntities = FALSE, asText = FALSE, trim = TRUE,
               isURL = FALSE, asTree = FALSE,
               useInternalNodes = FALSE, encoding = character())

Arguments

file | The name of the file containing the XML contents. This can contain ~ which is expanded to the user's home directory. It can also be a URL. See isURL. Additionally, the file can be compressed (gzip) and is read directly without the user having to de-compress (gunzip) it.
ignoreBlanks | logical value indicating whether text elements made up entirely of white space should be included in the resulting `tree'.
handlers | Optional collection of functions used to map the different XML nodes to R objects. Typically, this is a named list of functions, and a closure can be used to provide local data. This provides a way of filtering the tree as it is being created, adding or removing nodes, and generally processing them as they are constructed in the C code. In a recent addition to the package (version 0.99-8), if this is specified as a single function object, we call that function for each node in the underlying DOM tree. It is invoked with the new node and its parent node.
replaceEntities | logical value indicating whether to substitute entity references with their text directly. This should be left as False. The text still appears as the value of the node, but there is more information about its source, allowing the parse to be reversed with full reference information.
asText | logical value indicating that the first argument, `file', should be treated as the XML text to parse, not the name of a file. This allows the contents of documents to be retrieved from different sources (e.g. HTTP servers, XML-RPC, etc.) and still use this parser.
trim | whether to strip white space from the beginning and end of text strings.
validate | logical indicating whether to use a validating parser or not, or in other words check the contents against the DTD specification. If this is true, warning messages will be displayed about errors in the DTD and/or document, but the parsing will proceed except for the presence of terminal errors.
getDTD | logical flag indicating whether the DTD (both internal and external) should be returned along with the document nodes. This changes the return type.
isURL | indicates whether the file argument refers to a URL (accessible via ftp or http) or a regular file on the system. If asText is TRUE, this should not be specified. The function attempts to determine whether the data source is a URL by using grep to look for http or ftp at the start of the string. The libxml parser handles the connection to servers, not the R facilities (e.g. scan).
asTree | this only applies when on passes a value for the handlers argument and is used then to determine whether the DOM tree should be returned or the handlers object.
addAttributeNamespaces | a logical value indicating whether to return the namespace in the names of the attributes within a node or to omit them. If this is TRUE, an attribute such as xsi:type="xsd:string" is reported with the name xsi:type. If it is FALSE, the name of the attribute is type.
useInternalNodes | a logical value indicating whether to call the converter functions with objects of class XMLInternalNode rather than XMLNode. This should make things faster as we do not convert the contents of the internal nodes to R explicit objects. Also, it allows one to access the parent and ancestor nodes. However, since the objects refer to volatile C-level objects, one cannot store these nodes for use in further computations within R. They “disappear” after the processing the XML document is completed. If this argument is TRUE and no handlers are provided, the return value is a reference to the internal C-level document pointer. This can be used to do post-processing via XPath expressions using getNodeSet.
isSchema | a logical value indicating whether the document is an XML schema (TRUE) and should be parsed as such using the built-in schema parser in libxml.
fullNamespaceInfo | a logical value indicating whether to provide the namespace URI and prefix on each node or just the prefix. The latter (FALSE) is currently the default as that was the original way the package behaved. However, using TRUE is more informative and we will make this the default in the future.
encoding | a character string (scalar) giving the encoding for the document. This is optional as the document should contain its own encoding information. However, if it doesn't, the caller can specify this for the parser.

Details

The handlers argument is used similarly to those specified in xmlEventParse. When an XML tag (element) is processed, we look for a function in this collection with the same name as the tag's name. If this is not found, we look for one named startElement. If this is not found, we use the default built in converter. The same works for comments, entity references, cdata, processing instructions, etc. The default entries should be named comment, startElement, externalEntity, processingInstruction, text, cdata and namespace. All but the last should take the XMLnode as their first argument. In the future, other information may be passed via ..., for example, the depth in the tree, etc. Specifically, the second argument will be the parent node into which they are being added, but this is not currently implemented, so should have a default value (NULL).

The namespace function is called with a single argument which is an object of class XMLNameSpace. This contains begin{description} item[id] the namespace identifier as used to qualify tag names; item[uri] the value of the namespace identifier, i.e. the URI identifying the namespace. item[local] a logical value indicating whether the definition is local to the document being parsed. end{description}

One should note that the namespace handler is called before the node in which the namespace definition occurs and its children are processed. This is different than the other handlers which are called after the child nodes have been processed.

Each of these functions can return arbitrary values that are then entered into the tree in place of the default node passed to the function as the first argument. This allows the caller to generate the nodes of the resulting document tree exactly as they wish. If the function returns NULL, the node is dropped from the resulting tree. This is a convenient way to discard nodes having processed their contents.

Value

By default, an object of class XML doc is returned, which contains fields/slots named file, version and children.

file | The (expanded) name of the file containing the XML.
version | A string identifying the version of XML used by the document.
children | A list of the XML nodes at the top of the document. Each of these is of class XMLNode. These are made up of 4 fields. name The name of the element. attributes For regular elements, a named list of XML attributes converted from the <tag x="1" y="abc"> children List of sub-nodes. value Used only for text entries. Some nodes specializations of XMLNode, such as XMLComment, XMLProcessingInstruction, XMLEntityRef are used. If the value of the argument getDTD is TRUE, the return value is a list of length 2. The first element is as the document as described above. The second element is a list containing the external and internal DTDs. Each of these contains 2 lists - one for elements and another for entities. See parseDTD.

Note

Make sure that the necessary 3rd party libraries are available.

Author(s)

Duncan Temple Lang <duncan@wald.ucdavis.edu>

References

http://xmlsoft.org, http://www.w3.org/xml

See Also

xmlEventParse

Examples

 fileName <- system.file("exampleData", "test.xml", package="XML")
   # parse the document and return it in its standard format.
 xmlTreeParse(fileName)

   # parse the document, discarding comments.

 xmlTreeParse(fileName, handlers=list("comment"=function(x,...){NULL}), asTree = TRUE)

   # print the entities
 invisible(xmlTreeParse(fileName,
            handlers=list(entity=function(x) {
                                    cat("In entity",x$name, x$value,"\n")
                                    x}
                                  ), asTree = TRUE
                          )
          )

 # Parse some XML text.
 # Read the text from the file
 xmlText <- paste(readLines(fileName), "\n", collapse="")

 xmlTreeParse(xmlText, asText=TRUE)

    # with version 1.4.2 we can pass the contents of an XML
    # stream without pasting them.
 xmlTreeParse(readLines(fileName), asText=TRUE)

 # Read a MathML document and convert each node
 # so that the primary class is
 #   <name of tag>MathML
 # so that we can use method  dispatching when processing
 # it rather than conditional statements on the tag name.
 # See plotMathML() in examples/.
 fileName <- system.file("exampleData", "mathml.xml",package="XML")
m <- xmlTreeParse(fileName,
                  handlers=list(
                   startElement = function(node){
                   cname <- paste(xmlName(node),"MathML", sep="",collapse="")
                   class(node) <- c(cname, class(node));
                   node
                }))

  # In this example, we extract _just_ the names of the
  # variables in the mtcars.xml file.
  # The names are the contents of the <variable>
  # tags. We discard all other tags by returning NULL
  # from the startElement handler.
  #
  # We cumulate the names of variables in a character
  # vector named `vars'.
  # We define this within a closure and define the
  # variable function within that closure so that it
  # will be invoked when the parser encounters a <variable>
  # tag.
  # This is called with 2 arguments: the XMLNode object (containing
  # its children) and the list of attributes.
  # We get the variable name via call to xmlValue().

  # Note that we define the closure function in the call and then
  # create an instance of it by calling it directly as
  #   (function() {...})()

  # Note that we can get the names by parsing
  # in the usual manner and the entire document and then executing
  # xmlSApply(xmlRoot(doc)[[1]], function(x) xmlValue(x[[1]]))
  # which is simpler but is more costly in terms of memory.
 fileName <- system.file("exampleData", "mtcars.xml", package="XML")
 doc <- xmlTreeParse(fileName,  handlers = (function() {
                                 vars <- character(0) ;
                                list(variable=function(x, attrs) {
                                                vars <<- c(vars, xmlValue(x[[1]]));
                                                NULL},
                                     startElement=function(x,attr){
                                                   NULL
                                                  },
                                     names = function() {
                                                 vars
                                             }
                                    )
                               })()
                     )

  # Here we just print the variable names to the console
  # with a special handler.
 doc <- xmlTreeParse(fileName, handlers = list(
                                  variable=function(x, attrs) {
                                             print(xmlValue(x[[1]])); TRUE
                                           }), asTree=TRUE)

  # This should raise an error.
  try(xmlTreeParse(
            system.file("exampleData", "TestInvalid.xml", package="XML"),
            validate=TRUE))

## Not run:
 # Parse an XML document directly from a URL.
 # Requires Internet access.
 xmlTreeParse("http://www.omegahat.org/Scripts/Data/mtcars.xml", asText=TRUE)
## End(Not run)

  counter = function() {
              counts = integer(0)
              list(startElement = function(node) {
                                     name = xmlName(node)
                                     if(name %in% names(counts))
                                          counts[name] <<- counts[name] + 1
                                     else
                                          counts[name] <<- 1
                                  },
                    counts = function() counts)
            }

   h = counter()
   xmlTreeParse(system.file("exampleData", "mtcars.xml", package="XML"),  handlers = h, useInternalNodes = TRUE)
   h$counts()

 f = system.file("examples", "index.html", package = "XML")
 htmlTreeParse(readLines(f), asText = TRUE)
 htmlTreeParse(readLines(f))

  # Same as
 htmlTreeParse(paste(readLines(f), collapse = "\n"), asText = TRUE)

 getLinks = function() {
       links = character()
       list(a = function(node, ...) {
                   links <<- c(links, xmlGetAttr(node, "href"))
                   node
                },
            links = function()links)
     }

 h1 = getLinks()
 htmlTreeParse(system.file("examples", "index.html", package = "XML"), handlers = h1)
 h1$links()

 h2 = getLinks()
 htmlTreeParse(system.file("examples", "index.html", package = "XML"), handlers = h2, useInternalNodes = TRUE)
 all(h1$links() == h2$links())

  # Using flat trees
 tt = xmlHashTree()
 f = system.file("exampleData", "mtcars.xml", package="XML")
 xmlTreeParse(f, handlers = tt[[".addNode"]])
 xmlRoot(tt)

  # character set encoding for HTML
 f = system.file("exampleData", "9003.html", package = "XML")
   # we specify the encoding
 d = htmlTreeParse(f, encoding = "UTF-8")
   # get a different result if we do not specify any encoding
 d.no = htmlTreeParse(f)
   # document with its encoding in the HEAD of the document.
 d.self = htmlTreeParse(system.file("exampleData", "9003-en.html",package = "XML"))
   # XXX want to do a test here to see the similarities between d and
   # d.self and differences between d.no


Extract the contents of a leaf XML node

Description

Some types of XML nodes have no children nodes, but are leaf nodes and simply contain text. Examples are XMLTextMode, XMLProcessingInstruction. This function provides access to their raw contents. This has been extended to operate recursivel on arbitrary XML nodes that contain a single text node.

Usage

xmlValue(x, ignoreComments = FALSE)

Arguments

x | the XMLNode object whose contents are to be returned.
ignoreComments | a logical value which, if TRUE does not include the text in XML comment nodes. If this is FALSE, the text in the comments is part of the return value.

Value

The object stored in the value slot of the XMLNode object. This is typically a string.

Author(s)

Duncan Temple Lang

References

http://www.w3.org/XML, http://www.jclark.com/xml, http://www.omegahat.org

See Also

xmlChildren xmlName xmlAttrs xmlNamespace

Examples

 node <- xmlNode("foo", "Some text")
 xmlValue(node)

 xmlValue(xmlTextNode("some more raw text"))