Xml indent and newline for a new child

I have an xml file that looks like this.

<root>
    <children>
        <foo1 val="23"/>
        <foo2 val="14"/>
    </children>
</root>

      

I want to add a new child named foo in node using xmlNewChild () functions followed by xmlNewProp (). I would like to create something like the following.

<root>
    <children>
        <foo1 val="23"/>
        <foo2 val="14"/>
        <foo3 val="5"/>
    </children>
</root>

      

However, I always get the following.

<root>
    <children>
        <foo1 val="23"/>
        <foo2 val="14"/>
    <foo3 val="5"/></children>
</root>

      

I understand that libxml2 doesn't support white spaces by default. However, is there a way to achieve the result that I want? I need to get these tabs in front and new lines at the end for the newly added child.

Any help would be greatly appreciated. Thank!

+3


source to share


2 answers


The problem is that the XML structure looks something 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 node at the end children

, you can see that what you get is inevitable (since there is no node text to wrap a newline and the desired indentation between foo3

and children

).



You need to edit the final node text inside children

(the one right after foo2

) to give it extra padding, then add a new node, and then add the new node text to the padding </children>

. Alternatively, you can insert a node text identical to the previous text nodes inside children

, and then your new node element just before the final node text in children

. Both should give you the same output you want:

<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 an audit for the output created for libxml2. This will destroy the existing padding and redo it from scratch. Here is the appropriate answer.

+4


source


Use xmlTextWriterSetIndent



Link: http://xmlsoft.org/html/libxml-xmlwriter.html#xmlTextWriterSetIndent

0


source







All Articles