Search code examples
xmlxsltxmlstarlet

Replace part of URL in XML with xmlstarlet


I would like to replace a part of URL with XMLStarlet.

http://example.com:8081 to http://example2.com

XML:

<SHOP>
    <SHOPITEMS>
        <SHOPITEM>
            <IMGURL>http://example.com:8081/image.jpg</IMGURL>
            <IMAGES>
                <IMGURL>http://example.com:8081/image2.jpg</IMGURL>
                <IMGURL>http://example.com:8081/image3.jpg</IMGURL>
            </IMAGES>
        </SHOPITEM>
    </SHOPITEMS>
</SHOP>

As you can see the text I'd like to replace is on multiple levels in:

/SHOP/SHOPITEMS/SHOPITEM/IMGURL
/SHOP/SHOPITEMS/SHOPITEM/IMAGES/IMGURL

So far I tried:

xmlstarlet ed -u "//SHOP/SHOPITEMS/SHOPITEM/IMGURL/*[starts-with(text(), 'http://example.com:8081')]" -v http://example2.com input.xml

not worked... and:

xmlstarlet ed -u "//SHOP/SHOPITEMS/SHOPITEM/IMGURL/text()" -x "str:replace(., 'http://example.com:8081', 'http://example2.com')" input.xml

xmlXPathCompOpEval: function replace not found
Unregistered function
Segmentation fault

Any help is appreciated.


Solution

  • Not a real replace, but a substring trick. At least it works:

    xmlstarlet ed -u "//*[starts-with(text(),'http://example.com:8081/')]" -x "concat('http://example2.com/',substring(text(),25))" input.xml