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...
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.
attributes cannot contain multiple values (elements can)
You can't. Attribute names are unique per element.
... 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With