bash 如何使用xmlstarlet更新xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29265833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:38:22  来源:igfitidea点击:

how to update the xml file using xmlstarlet

xmlbashxmlstarlet

提问by Schu

I am using windows version of xmlstarlet to update an xml file, via windows batch file.

我正在使用 xmlstarlet 的 windows 版本通过 windows 批处理文件更新 xml 文件。

xml edit --update "/xml/table/rec[@id=3]/@id" --value 10 %xmlfile%

I expected this to update the id attribute of rec node to 10. When I run this I see the updated xml as expected in the command line, but the file is never updated.

我希望这会将 rec 节点的 id 属性更新为 10。当我运行它时,我在命令行中看到更新的 xml,但该文件从未更新。

How can I do it, I want to stay away rewriting the whole file as the file could be big one.

我该怎么做,我想避免重写整个文件,因为文件可能很大。

before update:

更新前:

<?xml version="1.0"?>
<xml>
  <table>
    <rec id="1" />
    <rec id="2" />
    <rec id="3" />
  </table>
</xml>

after update:

更新后:

<?xml version="1.0"?>
<xml>
  <table>
    <rec id="1" />
    <rec id="2" />
    <rec id="10" />
  </table>
</xml>

回答by Mathias Müller

You did not show your input document, but I assume it is the following, taken from the xmlstarlet documentation:

您没有显示您的输入文档,但我认为它是以下内容,取自xmlstarlet 文档

<xml>
  <table>
    <rec id="1">
      <numField>123</numField>
      <stringField>String Value</stringField>
    </rec>
    <rec id="2">
      <numField>346</numField>
      <stringField>Text Value</stringField>
    </rec>
    <rec id="3">
      <numField>-23</numField>
      <stringField>stringValue</stringField>
    </rec>
  </table>
</xml>

xmlstarlet modifies the file, but the result is sent to standard output, not saved in the original file. Use another option --inplaceto modify the file in place:

xmlstarlet 修改文件,但结果发送到标准输出,而不是保存在原始文件中。使用另一个选项--inplace来修改文件:

$ xml ed --inplace -u "/xml/table/rec[@id='3']/@id" -v 5 rec.xml

Then:

然后:

$ cat rec.xml
<?xml version="1.0"?>
<xml>
  <table>
    <rec id="1">
      <numField>123</numField>
      <stringField>String Value</stringField>
    </rec>
    <rec id="2">
      <numField>346</numField>
      <stringField>Text Value</stringField>
    </rec>
    <rec id="5">
      <numField>-23</numField>
      <stringField>stringValue</stringField>
    </rec>
  </table>
</xml>

By the way, this question seems to ask something very similar to this question.

顺便说一句,这个问题似乎提出了与这个问题非常相似的问题



EDIT: As suggested by @npostavs, this option is listed in the edit help:

编辑:根据@npostavs 的建议,此选项列在编辑帮助中:

$ xml edit --help
...
-L (or --inplace)   - edit file inplace
...