【问题标题】:how to update existing or create new XML node with Augeas如何使用 Augeas 更新现有的或创建新的 XML 节点
【发布时间】:2015-05-06 17:12:23
【问题描述】:

对于以下 XML:

<properties>
  <entry key="foo">bar</entry>
</properties>

我可以使用以下 augeas 命令更新带有“foo”属性的现有条目:

set /files/test.xml/properties/entry[#attribute/key='foo']/#text bar2

如果没有具有输入属性的现有条目,是否有 augeas 命令来创建一个新节点(具有键属性),并且如果具有输入属性的条目已经存在,则更新现有节点?我尝试了以下方法:

set /files/test.xml/properties/entry[#attribute/key='hello']/#text world

但这只会导致以下结果,没有属性:

<properties>
  <entry key="foo">bar2</entry>
  <entry>world</entry>
</properties>

【问题讨论】:

标签: xml puppet augeas


【解决方案1】:

/files/test.xml/properties/entry[#attribute/key='hello']/#text 不匹配任何节点,因此 Augeas 创建了一个新节点。如果你想同时更新这两个值。

显然,您只想保留一个entry 节点并同时设置其文本和key 属性:

defnode entry /files/test.xml/properties/entry[#attribute/key="foo"]
set $entry/#attribute/key 'hello'
set $entry/#text 'world'

【讨论】:

    【解决方案2】:

    假设你想要这个输出:

    <properties>
        <entry key="foo">bar</entry>
        <entry key="hello">world</entry>
    </properties>
    

    下面的代码应该可以解决问题:

    set /augeas/load/Xml/incl[2] /path/to/file.xml
    load
    defvar properties "/files/path/to/file.xml/properties"
    set $properties/entry[last()+1]/#attribute/key "hello"
    set $properties/entry[last()]/#text "world"
    save
    

    【讨论】:

    • 这可行,但不是幂等的。每次运行此脚本都会创建一个新条目,其中包含键“hello”和文本“world”。
    猜你喜欢
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多