Skip to content
Advertisement

How do I append or prepend to an attribute in an xml file using xmlstarlet or similar?

Did not see it in the docs. Here’s what I’m trying to do:

echo "<foo><bar t='A' /><bar t='B' /></foo>" | xmlstarlet ed -u "//bar/@t" -v "1_[//bar/@t]"

I want to pre-append the prefix 1_ to t.

Expected Output:

<?xml version="1.0"?>
<foo>
  <bar t="1_A"/>
  <bar t="1_B"/>
</foo>

Actual Output:

<?xml version="1.0"?>
<foo>
  <bar t="1_[//bar/@t]"/>
  <bar t="1_[//bar/@t]"/>
</foo>

Advertisement

Answer

Try this:

 echo "<foo><bar t='A' /><bar t='B' /></foo>" | 
      xmlstarlet ed -u "//bar/@t" -x 'concat("1_", .)'

-v is for fixed values, -x is for xpath expressions.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement