Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xml

xmlstarlet

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...

like image 282
Shadur Avatar asked Apr 12 '13 12:04

Shadur


People also ask

How do you change values in XML?

Change the Value of an Attribute In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values. The way to change the value of an attribute, is to change its text value. This can be done using the setAttribute() method or setting the nodeValue property of the attribute node.

Can attributes of XML element have multiple values?

attributes cannot contain multiple values (elements can)

Can XML elements have multiple attributes with same name?

You can't. Attribute names are unique per element.


1 Answers

... 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.

like image 67
Shadur Avatar answered Sep 24 '22 02:09

Shadur