如何使用Augeas更新现有的或创建新的XML节点

时间:2022-10-25 14:05:30

For the following XML:

对于以下XML:

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

I can update exiting entry with attribute "foo" with the following augeas command:

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

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

Is there augeas command(s) to create a new node (with key attribute) if there is no existing entry with the input attribute, and update existing if entry already exists with the input attribute? I tried the following:

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

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

But this only results in the following, without attribute:

但这只会产生以下结果,没有属性:

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

2 个解决方案

#1


/files/test.xml/properties/entry[#attribute/key='hello']/#text doesn't match any node, so Augeas creates a new node. If you want to update both values.

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

Apparently, you want to keep only one entry node and set both its text and key attribute:

显然,您只想保留一个入口节点并设置其文本和键属性:

defnode entry /files/test.xml/properties/entry
set $entry/#attribute/key 'hello'
set $entry/#text 'world'

#2


Assuming you want this output:

假设你想要这个输出:

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

The following code should do the trick:

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

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

#1


/files/test.xml/properties/entry[#attribute/key='hello']/#text doesn't match any node, so Augeas creates a new node. If you want to update both values.

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

Apparently, you want to keep only one entry node and set both its text and key attribute:

显然,您只想保留一个入口节点并设置其文本和键属性:

defnode entry /files/test.xml/properties/entry
set $entry/#attribute/key 'hello'
set $entry/#text 'world'

#2


Assuming you want this output:

假设你想要这个输出:

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

The following code should do the trick:

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

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