Jason Youn
Jason Youn

Reputation: 55

xml indent and newline for new child

I have a xml file that looks like a following.

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

I wish to add a new child with name foo to the node using the functions xmlNewChild() followed by xmlNewProp(). I would like to generate something like the following.

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

However, I always end up with the following.

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

I do understand that libxml2 does not favor white spaces by default. However, is there a way to achieve the result I want? I need to get those tabs in front and newlines in the end for the newly added child.

Any help would be appreciated. Thanks!

Upvotes: 3

Views: 2902

Answers (2)

singingsingh
singingsingh

Reputation: 1434

Use xmlTextWriterSetIndent

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

Upvotes: 0

Amadan
Amadan

Reputation: 198324

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.

Upvotes: 4

Related Questions