Set the text value of a node using xpath
XPath by itself cannot be used to modify XML documents. But the xmlstarlet command line utility can do it. Example:
xml ed -u "//book[1]/title" -v "Game of Thrones" bookstore.xml
Output:
<?xml version="1.0" encoding="ISO-8859-1"?><bookstore> <book> <title lang="eng">Game of Thrones</title> <price>29.99</price> </book> <book> <title lang="eng">Learning XML</title> <price>39.95</price> </book></bookstore>
Note: without [1]
in the expression, the result would be:
<?xml version="1.0" encoding="ISO-8859-1"?><bookstore> <book> <title lang="eng">Game of Thrones</title> <price>29.99</price> </book> <book> <title lang="eng">Game of Thrones</title> <price>39.95</price> </book></bookstore>
The command above outputs the result to stdout. There is an option (-L
or --inplace
) that modifies the document in place:
xml ed -L -u "//book[1]/title" -v "Game of Thrones" bookstore.xml
This option is not mentioned in the documentation for xmlstarlet 1.3.1, but it is shown when executing
xml ed --help
As far as I know, XPath itself cannot be used for that, because it's only a query language, so it's not for creation or modification of XML files. You'll need some other tool for that. If you're into command line tools, maybe check xsltproc
, which is a part of libxslt
. I'm not an XSLT expert, but a quick look at the linked page gives me a feeling that you can achieve the desired result with <if>
and <value-of>
. Or you could parse XML with regular expressions, but please don't, I hear it's a slippery slope.