使用xpath设置节点的文本值

gdo*_*eod 4 xml bash xpath

示例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>
Run Code Online (Sandbox Code Playgroud)

我在shell上使用xpath尝试更改xml节点的文本值.我想把哈利波特变成托恩斯的游戏.

xpath test.xml "//bookstore/book/title/text()" 2>/dev/null
Run Code Online (Sandbox Code Playgroud)

哈利波特会回到我的终端.现在是否有可能使用xpath将节点的值从哈利波特改为Game of Thornes?

谢谢!

mzj*_*zjn 8

XPath本身不能用于修改XML文档.但xmlstarlet命令行实用程序可以执行此操作.例:

xml ed -u "//book[1]/title" -v "Game of Thrones" bookstore.xml
Run Code Online (Sandbox Code Playgroud)

输出:

<?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>
Run Code Online (Sandbox Code Playgroud)

注意:如果没有[1]在表达式中,结果将是:

<?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>
Run Code Online (Sandbox Code Playgroud)

上面的命令将结果输出到stdout.有一个选项(-L--inplace)可以修改文档:

xml ed -L -u "//book[1]/title" -v "Game of Thrones" bookstore.xml 
Run Code Online (Sandbox Code Playgroud)

xmlstarlet 1.3.1的文档中未提及此选项,但在执行时会显示该选项

xml ed --help
Run Code Online (Sandbox Code Playgroud)