3

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!

2 Answers 2

4

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.

1
  • I realized that the xmlKeepBlanksDefault(0); needed to be set before parsing the file. It does auto indent for us, which would be good enough for my purpose. But definitely text method is worth a try. Thanks.
    – Jason Youn
    May 28, 2015 at 8:42
0

Use xmlTextWriterSetIndent

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.