Changing the value of an XML element depending on the value of another element in the tree

I have a very large (100+ megabyte uncompressed) XML file storing datasets, and I'm trying to selectively change some values.

For example, say sample.xml looks like this:

<objects>
  <object>
    <name>Foo</name>
    <constant1>10</constant1>
    <constant2>20</constant2>
  </object>
  <object>
    <name>Bar</name>
    <constant1>15</constant1>
    <constant2>40</constant2>
  </object>
<objects>

Now I want to change the value of <constant1> to 18, but only for the object whose Name element has value Foo. I've been poking at the XML Starlet documentation but its article on editing only has examples on how to look for attributes of elements directly up in the tree, unless I'm missing something...

Upvotes: 6

Views: 5644

Answers (1)

... Apparently I'm an idiot; As demonstrated in this answer you can search for element values the same way you can search for attribute values, so the correct command would be:

xmlstarlet ed -u '//object[name="Foo"]/const1' -v 18 sample.xml

... Also, caveat when working on really big files: Without output redirection, xmlstarlet prints to stdout. All 100+ megabytes of xml. Oops.

Upvotes: 13

Related Questions