【问题标题】:Adding new lines and tabs in XML using Augeas使用 Augeas 在 XML 中添加新行和制表符
【发布时间】:2020-08-06 19:09:08
【问题描述】:

这与我之前使用 Augeas 更新 xml 的 post 有关。我手动调整了格式,并能够查看新行和制表符是如何在 augtool 中添加和解析的。我尝试添加这些新行,但无法在 items 节点和子 item 节点之间插入每个 #text 行。是否可以通过为 items/#text 设置新变量来添加新的行和选项卡?

使用 Augeas 插入这些字符是否可行?

        <FileTypes>
        <items>
        <item value="video/*"/>
        <item value="audio/*"/>
        <item value="application/rar"/>
        </items>
        </FileTypes>      
/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[1] = "\n\t\t"
/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/#text[2] = "\t\t"
/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/#text[3] = "\t\t"
/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"

我在下面有这样的东西来插入一个新行,但它似乎没有工作,只添加了一个文字换行符和制表符。

set /files/opt/webapp/config.xml/File/FileTypes/items/#text \n\t\t'

这会导致更糟糕的情况。

        <FileTypes>
        <items>\n\t\t<item value="video/*"/>
<item value="audio/*"/>
<item value="application/rar"/>
</items>
        </FileTypes>      

【问题讨论】:

    标签: xml augeas


    【解决方案1】:

    我想出了一个优雅的幂等解决方案,以确保您的 &lt;item&gt; 节点由一个列表缩进。这是一个建议:

    # define $audio (see previous question)
    defnode audio item[#attribute/value="audio/*"] "#empty"
    
    # define $noindent as $audio if the immediate previous node is not a `#text` one
    defvar noindent $audio[preceding-sibling::*[1][label()!="#text"]]
    
    # insert a #text element before $noindent. Will fail silently if $noindent doesn't match anything, making the change idempotent
    ins #text before $noindent
    
    # Set the value of the next #text node, which we are sure exists now
    set #text[following-sibling::*[1][#attribute/value="audio/*"]] "\t"
    

    一般来说,#text 工作正常,而您的问题很可能是对值的错误引用。

    【讨论】:

    • 非常感谢您对答案的帮助和快速响应。你能告诉我应该把代码放在哪里来设置像set $audio/#attribute/value "audio/*"这样的元素值吗?我把它放在ins #text before $noident 之后,它似乎可以解决问题。在运行测试时,我还注意到,如果有人手动移动并更改各种文件类型的 item 元素等内容,格式化 n 位置可能会出错。或者我可能做得不对:) 仍然会继续使用您的示例尝试不同的方法。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多