简体   繁体   中英

How to edit XML file in R {XML}

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM