xml indent and newline for new child

有些话、适合烂在心里 提交于 2019-12-06 01:59:52
Amadan

The issue is that the XML structure actually looks like this:

<root>
    [TEXT:"\n    "]
    <children>
        [TEXT:"\n        "]
        <foo1 val="23"/>
        [TEXT:"\n        "]
        <foo2 val="14"/>
        [TEXT:"\n    "]
    </children>
    [TEXT:"\n"]
</root>

If you just add an extra element node at the end of children, you can see that what you get is inevitable (as there is no text node to carry a newline and the desired indentation between foo3 and children).

You need to edit the final text node inside children (the one immediately after foo2) to give it an extra indent, then append your new node, then append a new text node to indent </children>. Alternately, you can insert a text node identical to previous text nodes inside children and then your new element node just before the final text node in children. Both should give you the same result, the one you need:

<root>
    [TEXT:"\n    "]
    <children>
        [TEXT:"\n        "]
        <foo1 val="23"/>
        [TEXT:"\n        "]
        <foo2 val="14"/>
        [TEXT:"\n        "]
        <foo3 val="5"/>
        [TEXT:"\n    "]
    </children>
    [TEXT:"\n"]
</root>

Another approach is to have libxml2 autoindent the output for you. This will destroy existing indentation and redo it from scratch. Here is a relevant answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!