4

Example XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>
</bookstore>

I am using xpath on my shell to try and change the text value of an xml node. I would like to change Harry Potter to Game of Thornes.

xpath test.xml "//bookstore/book/title/text()" 2>/dev/null

Will echo out Harry Potter to my terminal. Now is it possible to use xpath to change the value of the node from Harry Potter to Game of Thornes?

Thanks!

gdoubleod
  • 1,268
  • 3
  • 19
  • 33

2 Answers2

8

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
mzjn
  • 48,958
  • 13
  • 128
  • 248
  • Awesome! you are a gentleman and a scholar. The method you gave above actually echos the result to standard output. I had to add >> new_file.xml is there a way to make xmlstarlet edit the file in place or should i just move the file after that to over write the old oneL? – gdoubleod Apr 09 '12 at 19:06
  • I have a file that starts with the following definition if i run the cmd you mentioned it does nothing, until and unless i change the root tag to Is this a bug or something that i misunderstand? Thank you – Marwan Jaber Feb 03 '15 at 14:17
1

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.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175