[R] How to modify XML documents and save changes

Stephen C. Upton upton at mitre.org
Tue Feb 25 17:42:30 CET 2003


As with most R objects, you're basically putting a copy of the R object into
the new object. Any operation or function you apply to that object does not
affect the original. Same goes for append.xmlNode - you're appending to the
original and getting back another structure that is the original plus the
new node. Finally, saveXML works on an object of XMLInternalDocument and doc
(the object returned by xmlTreeParse) is a XMLDocument object.

Here's one suggestion:
1. Read in the doc object as you've done, but manipulate the structure as
you would any other R object, e.g.,
QTListNode [[1]] <-
2. you then need to modify that node within the root with this new, modified
node, e.g. (assume I've assigned root <- xmlRoot(doc)),
root[[whateverindextagnameis]] <- QTListNode[[1]]
(I use the index here rather than the name, since it's unique - if you use a
name,e.g., root[["tagname"]], that just adds a list element to root with
name "tagname")
3. to write out, use write with toString.XMLNode,
write(toString.XMLNode(root, file="out.xml")

Since this is probably a little cumbersome, suggest writing a function to do
the finding, appending, and replacement.

A little cumbersome, but doable. One other option is to use xmlEventParse
and write a handler that would add the element after the one you're
interested in.  I hope there is a better way, but haven't seen it yet. :-(


Steffen Durinck wrote:

> Dear,
> I want to read XML documents, add child nodes to some elements and store
> everything back as an XML document.
> I've tryed the following:
> doc <- xmlTreeParse("file.xml")
> QTListNode<-xmlElementsByTagName(xmlRoot(doc)[[1]],"tagname")
> append.xmlNode(QTListNode[[1]],newXMLNode(name ="Norm", attrs = NULL))
> saveXML(doc, file = "out.xml", compression = 0, indent=T)
> This doesn't seem to work.
> Can anyone help?
> Thanks,
> Steffen
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help

More information about the R-help mailing list