示例 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>
我在我的 shell 上使用 xpath 来尝试更改 xml 节点的文本值。我想将《哈利·波特》改为《权力的游戏》。
xpath test.xml "//bookstore/book/title/text()" 2>/dev/null
将哈利波特回显到我的终端。现在是否可以使用 xpath 将节点的值从 Harry Potter 更改为 Game of Thornes?
谢谢!
最佳答案
XPath 本身不能用于修改 XML 文档。但是 xmlstarlet命令行实用程序可以做到这一点。示例:
xml ed -u "//book[1]/title" -v "Game of Thrones" bookstore.xml
输出:
<?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>
注意:如果表达式中没有 [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>
上面的命令将结果输出到标准输出。有一个选项(-L
或 --inplace
)可以就地修改文档:
xml ed -L -u "//book[1]/title" -v "Game of Thrones" bookstore.xml
这个选项在xmlstarlet 1.3.1的文档中没有提到,但是在执行的时候会显示
xml ed --help
关于xml - 使用 xpath 设置节点的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10070746/