操作方法:调试 XML 结构并替换节点的值
由于您可能想用不同的结构和节点更改您自己的 XML 文件,因此可能很难找到正确的语法来更改值。
以下实践展示了如何以交互模式(即调试)导航通过任何 xml 文件以找到节点(即语法)应该被替换。
xmllint --shell file.xml # starts xmllint in interactive mode
setrootns
cat # shows the complete XML structure
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:aut="http://">
<soapenv:Header>
<aut:Session>
<aut:IPAddress>127.0.0.1</aut:IPAddress>
<aut:SessionToken>true</aut:SessionToken>
<aut:ApplicationToken>861</aut:ApplicationToken>
</aut:Session>
</soapenv:Header>
<soapenv:Body></soapenv:Body>
</soapenv:Envelope>
现在您可以通过 XML 树逐步走到所需的节点:
cd //soapenv:Envelope # change to the first level
soapenv:Envelope > # the prompt changes on success
cd //soapenv:Envelope/soapenv:Header/aut:Session
aut:Session > # appropriate prompt change
cat
<aut:Session>
<aut:IPAddress>127.0.0.1</aut:IPAddress>
<aut:SessionToken>true</aut:SessionToken>
<aut:ApplicationToken>861</aut:ApplicationToken>
</aut:Session>
直接显示某个节点/路径的结构和值(无需事先cd):
cat //soapenv:Envelope/soapenv:Header/aut:Session
<aut:Session>
<aut:IPAddress>127.0.0.1</aut:IPAddress>
<aut:SessionToken>true</aut:SessionToken>
<aut:ApplicationToken>861</aut:ApplicationToken>
</aut:Session>
请记住,路径末尾不要有斜杠,因为它找不到节点:
cat //soapenv:Envelope/soapenv:Header/aut:Session/ # trailing slash throws an error
XPath error : Invalid expression
//soapenv:Envelope/soapenv:Header/aut:Session/
^
//soapenv:Envelope/soapenv:Header/aut:Session: no such node
假设我们想更改 IP 地址,最好先检查正确的路径:
cat //soapenv:Envelope/soapenv:Header/aut:Session/aut:IPAddress
<aut:IPAddress>127.0.0.1</aut:IPAddress>
或者只是获取节点的值:
cat //soapenv:Envelope/soapenv:Header/aut:Session/aut:IPAddress/text()
127.0.0.1
先改成合适的路径:
cd //soapenv:Envelope/soapenv:Header/aut:Session/aut:IPAddress
aut:IPAddress > cat text() # alternative way to check the value
127.0.0.1
aut:IPAddress > set 1.1.1.1 # change the value
aut:IPAddress > cat text() # crosscheck the changed value
1.1.1.1
aut:IPAddress > save # save changes to file
aut:IPAddress > save backup.xml # save changes to another file
aut:IPAddress > quit
help 在交互模式下将显示有关命令的更多详细信息。 https://gnome.pages.gitlab.gnome.org/libxml2/xmllint.html#shell 还提供了有关 shell 命令的详细信息。
一旦确定了节点的正确路径(应该更改),您就可以参考上面的@LMCs 一行来动态更改 XML 文件。