Reputation: 315
I have seen some similar threads on this, but none that seem to answer my questions exactly:
I have an XML file of a building with several "Space" objects. I'm trying to replace the "ID" attribute of the Space with the "Name" value under the space. For a simplified example:
<Space zoneIdRef="idref text" id="id text">
...
...
...
<Name>"name text"</Name>
</Space>
So I want to end up with Space id="name text" instead of "id text".
What I have tried so far:
rm(list = ls())
file = "C://Users//ben.brannon//Desktop//Project1.xml"
outfile = "C://Users//ben.brannon//Desktop//Project1_new.xml"
xml = xmlTreeParse(file)
root = xmlRoot(xml)
n=4
for (i in 3:3+n-1)
{
name = xmlSApply(root[["Campus"]][["Building"]][[i]][["Name"]],xmlValue)
spaceattrs = xmlAttrs(root[["Campus"]][["Building"]][[i]])
}
saveXML(root, outfile)
When I check the new values in "root" within R, it seems to have updated correctly, but when I write the file, they haven't been changed. I'm wondering if there's a better way to update the value than just with an "=", or maybe I'm not dealing with the text strings correctly?
Thanks,
Upvotes: 0
Views: 1193
Reputation: 2544
Simple assignment should suffice.
XML:
<Root>
<Campus>
<Building>
<Space zoneIdRef="idref text" id="id text">
<Name>"name text"</Name>
</Space>
</Building>
</Campus>
</Root>
Code:
library(XML)
xml <- xmlTreeParse("XML.xml")
root = xmlRoot(xml)
name = xmlValue(root[["Campus"]][["Building"]][["Space"]][["Name"]])
xmlAttrs(root[["Campus"]][["Building"]][["Space"]])[["id"]] <- name
Upvotes: 2