问题描述
我有一个如下所示的xml文件.
I have a xml file that looks like a following.
<root>
<children>
<foo1 val="23"/>
<foo2 val="14"/>
</children>
</root>
我希望使用功能 xmlNewChild()后跟 xmlNewProp()将名称为 foo 的新子代添加到节点.我想生成类似以下的内容.
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>
我确实知道libxml2默认情况下不支持空格.但是,有没有一种方法可以达到我想要的结果?对于新添加的孩子,我需要将这些标签放在开头,最后将换行符放在上面.
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!
推荐答案
问题是XML结构实际上看起来像这样:
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>
如果仅在children
的末尾添加一个额外的元素节点,则可以看到所得到的结果是不可避免的(因为没有文本节点可以承载换行符,并且foo3
和).
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
).
您需要编辑children
中的最后一个文本节点(紧接在foo2
之后的文本节点)以为其提供额外的缩进,然后附加新节点,然后将新文本节点附加到缩进</children>
中.或者,您可以在children
中插入与先前的文本节点相同的文本节点,然后在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>
另一种方法是让libxml2为您自动缩进输出.这将破坏现有的缩进并从头开始重做. 此处是一个相关的答案.
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.
这篇关于新孩子的xml缩进和换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!