1

I would like to programmatically update a string in a very simple XML config file, such as this:

<?xml version="1.0"?>
<x>
    <z>should be changed</z>
</x>
<y>
    <z>should NOT be changed</z>
</y>

Does a simple CLI command exist that will update x/z and NOT y/z ? Perhaps with an XPath selector argument, such as:

$ xml-update myfile.xml /x/z "my new string"

I could write something in Perl or Python, but given the simplicity of this problem, I guess there must be a clever Unix utility that does this already.

Update: I found this but it seems a bit overkill. And I would have to learn XSLT first. http://developerblog.redhat.com/2013/12/05/xml-editing-bash-script/

3

You can use the xml2/2xml tools to process XML on the command line without too much fuss. xml2 converts an XML document into a line-oriented format suitable for use with traditional text processing tools like awk or sed, and 2xml takes this format and converts it back to XML.

For your example, if I take this document:

<?xml version="1.0"?>
<doc>
<x>
    <z>should be changed</z>
</x>
<y>
    <z>should NOT be changed</z>
</y>
</doc>

Running xml2 on that content yields:

$ xml2 < doc.xml
/doc/x/z=should be changed
/doc/y/z=should NOT be changed

I can modify the content of the <z> element like this

xml2 < doc.xml |
sed '/\/doc\/x\/z/ s/should be changed/look ma no hands/' |
2xml | tidyp -xml -i -q

I'm using a sed search expression to look explicitly for the line starting with /doc/y/z, and then modifying the content of that line, which gives us:

<doc>
  <x>
    <z>look ma no hands</z>
  </x>
  <y>
    <z>should NOT be changed</z>
  </y>
</doc>

I passed the output through tidyp, an XML formatter, because otherwise the document would look like:

<doc><x><z>look ma no hands</z></x><y><z>should NOT be changed</z></y></doc>

...which is syntactically correct but harder to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.