Jonathan
Jonathan

Reputation: 175

How to edit a value in xml in R? {XML}

I am trying to edit a value in a xml file. I was able to find what I want to edit, but I am getting a subsettable error.I could find the value I want to change using normalize-space, i.e. it gives me the number I want to change.

EDIT 1: adding reproducible xml file as example

<variable_1>
    <variable_1_1>
        <variable_a>
            <variable_doesnt_mather_a>1</variable_doesnt_mather_a>
            <variable_that_I_want type="text"  description="this is the one I want to change!">300</variable_that_I_want>
        </variable_a>
        <variable_b>
            <variable_doesnt_mather_b>2</variable_doesnt_mather_b>
        </variable_b>
    </variable_1_1>
    <variable_1_2>
        <variable_12a>
            <variable_doesnt_mather_12a>3</variable_doesnt_mather_12a>
        </variable_12a>
        <variable_12b>
            <variable_doesnt_mather_12b>4</variable_doesnt_mather_12b>
        </variable_12b>
    </variable_1_2>
</variable_1>

I tried:

> library(XML)
> xml = xmlParse('XML.xml')
> xml[['normalize-space(//variable_that_I_want)']]
[1] "300"

But if I simply try to change to, for example, 100... then R is not happy anymore:

> xml[['normalize-space(//variable_that_I_want)']] = 100 #or "100" gives same error

Error in xml[["normalize-space(//variable_that_I_want)"]] = 100 : object of type 'externalptr' is not subsettable

Alternatively I was able to find with getNode

> getNodeSet(xml, '//variable_that_I_want')[[1]]
<variable_that_I_want type="text" description="Description of what I want">300</variable_that_I_want >

But still don't know how to change the 300 to 100.

Upvotes: 0

Views: 564

Answers (1)

RoB
RoB

Reputation: 1994

You will probably have an easier time with this by using the xml2 package. I've done what you wanted with it like so :

library(xml2)
xml_file <- "~/Desktop/tests/test.xml" # your file 
x <- read_xml(xml_file)

to_mod <- xml_find_all(x, "//variable_that_I_want")
xml_text(to_mod)
# [1] "300"
xml_text(to_mod) <- "100"
xml_text(to_mod)
# [1] "100"

xml_find_all(x, "//variable_that_I_want")
#{xml_nodeset (1)}
#[1] <variable_that_I_want type="text" description="this is the one I want to change!">100</variable_that_I_want>

Upvotes: 1

Related Questions