Po78
Po78

Reputation: 183

Replace nodes in xml

Is anyone have I idea how to replace xml nodes using XML library (or any other R libraries):

Here an example:

<str>
  <head>
    <id>1234</id>
  </head>
  <elements>
    <other>
        <code>Y</code>
    </other>
    <element id=1>
        <code>A</code>
        <code>B</code>
        <code>C</code>
    </element>
    <element id=2>
        <code>D</code>
        <code>E</code>
        <code>F</code>
    </element>
  </elements>
</str>

I woulid like to replace only whildren in element tag with id=2:

<code>D</code>
<code>E</code>
<code>F</code>

by:

<code>G</code>
<code>H</code>

(Note that number of code to replaced are not the same, here 3 codes to replace by 2, but it could be 2 to replace by 3, or any other combinaison) in node element id=2, to finaly have:

<str>
  <head>
    <id>1234</id>
  </head>
  <elements>
    <annex>
        <txt>Annex 1</txt>
        <txt>Annex 2</txt>
    </annex>
    <other>
        <code>Y</code>
    </other>
    <element id=1>
        <code>A</code>
        <code>B</code>
        <code>C</code>
    </element>
    <element id=2>
        <code>G</code>
        <code>H</code>
    </element>

  </elements>
</str>

Upvotes: 2

Views: 149

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

Here's an example using xml2. Note that your input has to be valid XML - in your example, the last <element> should be </element>. Anyway, making this change and saving it as test.xml, I can do

library(xml2)

doc <- read_xml("test.xml")
nodes <- xml_find_all(doc, "//element/code")
xml_text(nodes) <- c("D", "E", "F")
write_xml(doc, "test2.xml")

And now I have the file test2.xml which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<str>
  <head>
    <id>1234</id>
  </head>
  <elements>
    <annex>
      <txt>Annex 1</txt>
      <txt>Annex 2</txt>
    </annex>
    <other>
      <code>Y</code>
    </other>
    <element>
      <code>D</code>
      <code>E</code>
      <code>F</code>
    </element>
  </elements>
</str>

Upvotes: 1

Related Questions