【问题标题】:Adding new nodes to XML file with Augeas使用 Augeas 将新节点添加到 XML 文件
【发布时间】:2020-08-05 15:10:41
【问题描述】:

我有这个 XML 文件 /opt/webapp/config.xml 用于包含父节点 items 的自定义 web 应用程序。

<items>
</items>

我正在尝试添加具有 value 属性的新子节点 item 列表,同时确保子节点不包含结束/结束标记,因为该应用需要该格式。

<items>
<item value="video/*"/><item value="audio/*"/><item value="application/rar"/><item value="application/x-zip"/><item value="application/x-gzip"/>
</items>

如果我使用 augtool 打开现有配置,我将得到以下输出。

/files/opt/webapp/config.xml/File/FileTypes
/files/opt/webapp/config.xml/File/FileTypes/#text = "\n"
/files/opt/webapp/config.xml/File/FileTypes/items
/files/opt/webapp/config.xml/File/FileTypes/items/#text = "\n"
/files/opt/webapp/config.xml/File/FileTypes/items/item[1] = "#empty"
/files/opt/webapp/config.xml/File/FileTypes/items/item[1]/#attribute
/files/opt/webapp/config.xml/File/FileTypes/items/item[1]/#attribute/value = "video/*"
/files/opt/webapp/config.xml/File/FileTypes/items/item[2] = "#empty"
/files/opt/webapp/config.xml/File/FileTypes/items/item[2]/#attribute
/files/opt/webapp/config.xml/File/FileTypes/items/item[2]/#attribute/value = "audio/*"
/files/opt/webapp/config.xml/File/FileTypes/items/item[3] = "#empty"
/files/opt/webapp/config.xml/File/FileTypes/items/item[3]/#attribute
/files/opt/webapp/config.xml/File/FileTypes/items/item[3]/#attribute/value = "application/rar"

我发现了一些帖子 here 和 here 讨论关于 xml 和 Augeas,但这些示例遵循带有开始和结束标记的格式。例如:&lt;item value="application/rar"&gt;&lt;/item&gt;。而且我正在尝试寻找一种方法来查看 Augeas 是否也可以创建和添加仅带有自闭合标签的子节点。

我在 RHEL 7 上使用 puppet agent 5.5.10 附带的 augtool(版本 1.10.1)。

谢谢。

【问题讨论】:

    标签: xml augeas


    【解决方案1】:

    如您在示例中所见,自闭合标签的值为 #empty,因此您只需在项目上设置该值。

    所以在你的情况下,你可以这样做:

    # set context to use relative paths later
    set /augeas/context /files/opt/webapp/config.xml/File/FileTypes/items
    
    # define a $video variable pointing to the video element, define it as self-closing
    defnode video item[#attribute/value="video/*"] "#empty"
    # Set element value
    set $video/#attribute/value "video/*"
    
    defnode audio item[#attribute/value="audio/*"] "#empty"
    set $audio/#attribute/value "audio/*"
    
    defnode rar item[#attribute/value="application/rar"] "#empty"
    set $rar/#attribute/value "application/rar"
    

    等等

    导致:

    <items>
    <item value="video/*"/>
    <item value="audio/*"/>
    <item value="application/rar"/>
    </items>
    

    defnode 将定义一个指向节点的变量,如果它还不存在则设置它的值。因此,这段代码将是幂等的。

    【讨论】:

    • 谢谢。这完全符合我的预期。还刚刚发现 Augeas 会负责添加和修改配置,但不会处理缩进和格式化。猜猜这必须单独完成。
    • 是的,Augeas 愿意忽略格式。如果您关心它,则需要为此使用格式化程序/美化器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多