[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 [] <-
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[]
(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
3. to write out, use write with toString.XMLNode,
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:
> 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")
> append.xmlNode(QTListNode[],newXMLNode(name ="Norm", attrs = NULL))
> saveXML(doc, file = "out.xml", compression = 0, indent=T)
> This doesn't seem to work.
> Can anyone help?
> R-help at stat.math.ethz.ch mailing list
More information about the R-help