Duncan Temple Lang
Dept. of Statistics, UC Davis

# Modifying XML

## Overview

This short article shows how we can read an

XML document in R and modify it in place and then serialize it, e.g. to another file. We'll take a somewhat realistic example. We want to take an XML documentation file describing an R function and change the URL for the author and add an additional item to the see also list. Also, we will insert a new example. The document we consider is the file treeParseHelp.xml. It is not a standard format, but comes from work we did a long time ago in considering an XML format for the R documentation files. The contents of the document are given at the end of this document.

As with most things dealing with XML, there are various alternative approaches, e.g. using XSL and so on. This is just one.

We start by reading the document into R. We keep the tree at the C-level rather than creating R representations of the nodes. fileName = "~/Projects/org/omegahat/XML/RSHelp/examples/treeParseHelp.xml" doc = xmlTreeParse(fileName, useInternalNodes = TRUE) The next thing we want to do is to find the author. We can do this by matching names or using an XPath query: author = getNodeSet(doc, "//shelp:authors/shelp:author", namespace = c(shelp = 'http://www.omegahat.net/XML/RShelp'))[[1]] If we want to see what this looks like, we can coerce it to a string as(author, "character") or alternatively we can query its name, attributes, children, etc. But we know that this has child named 'a' with an href attribute which we want to change. We could have fetched this directly in the XPath query. But to change it we can do xmlAttrs(author[[1]]) = c(href='http://www.stat.ucdavis.edu/~duncan')

Now to add an entry to the 'See also' section, we find the 'shelp:seealso' node. xmlRoot(doc)

## The Document