0

I am creating a bash script to replace various values in a large XML file using XMLStarlet. For one specific situation I fail to find the proper XMLStarlet commandline syntax.

I created a simplified XML file (test.xml) to show my situation:

<?xml version="1.0"?>
<DATA VERSION="1.0">
  <TABLES>
    <ITEM>
      <ID>1234</ID>
      <prop3>ABCD</prop3>
    </ITEM>
    <ITEM>
      <ID>5678</ID>
      <prop3>EFGH</prop3>
    </ITEM>
  </TABLES>
</DATA>

I am trying to replace prop3 of an ITEM with a specific ID (e.g. 5678). I found a very similar question/reply on stackoverflow which gave me good hopes to bring me to the solution. It definitely helped but only partially.

I constructed the below command but it is not entirely right since it has no effect (XML unchanged):

xmlstarlet ed -u "/DATA/TABLES/ITEM[@ID='5678']/prop3" -v "succes" test.xml
4
  • 2
    ITEM[@ID='5678'] matches a tag with an ID attribute like <ITEM ID="5678"> but your sample xml document doesn't use attributes, thus nothing matches the xpath expression. Commented Nov 9, 2023 at 16:31
  • 1
    Make it look for a child element named ID instead by removing the @. Commented Nov 9, 2023 at 16:54
  • You might want to add that as an answer @Shawn Commented Nov 9, 2023 at 18:38
  • @glennjackman Now that I'm at a computer again, done. Commented Nov 9, 2023 at 20:52

2 Answers 2

1

The XPath fragment ITEM[@ID='5678'] looks for an ITEM element with a matching ID attribute: <ITEM ID="5678">. Your sample XML document doesn't use attributes on ITEM elements, thus nothing in it will match. To match an element with a matching child element, drop the @ and it'll make the replacement:

$ xmlstarlet ed -u "/DATA/TABLES/ITEM[ID='5678']/prop3" -v "succes" test.xml
<?xml version="1.0"?>
<DATA VERSION="1.0">
  <TABLES>
    <ITEM>
      <ID>1234</ID>
      <prop3>ABCD</prop3>
    </ITEM>
    <ITEM>
      <ID>5678</ID>
      <prop3>succes</prop3>
    </ITEM>
  </TABLES>
</DATA>
Sign up to request clarification or add additional context in comments.

Comments

-1

Thanks everyone.

xmlstarlet ed -u "/DATA/TABLES/ITEM[ID='5678']/prop3" -v "succes" test.xml

It works. I learned something more about XML.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.