gpt4 book ai didi

c++ - 使用 libxml2 缩进合并的 xml 文件

转载 作者:行者123 更新时间:2023-11-30 05:19:25 33 4
gpt4 key购买 nike

我正在尝试使用 libxml2 和 C++ 合并两个 xml 文件。
这些 xml 文件具有相同的架构但具有不同的内容,我需要将一些元素合并到主 xml 文件中。而且这些xml文件有不同的缩进。 (一个有空格另一个有制表符)

这是我的伪代码:

xmlDocPtr doc1 = xmlParseFile(...);
xmlDocPtr doc2 = xmlParseFile(...);

xmlNodePtr node_from_doc1;
for (node; ...) {
...
xmlAddNextSibling(node_from_doc1, node);
...
}

xmlSaveFormatFile("merged.xml", doc1, 1);

合并后的xml文件缩进不好。

<root_elem attr1="attr">
...
<child>child_text</child>
<child_merged>child_merged</child_merged>
</root_elem>

'child' 元素和 'child_merged' 元素应该有相同的缩进。

如何缩进合并后的文件?提前致谢。

最佳答案

文档说:“请注意,只有在 xmlIndentTreeOutput = 1xmlKeepBlanksDefault(0) 被调用时,format = 1 才提供节点缩进。 "

您的伪代码示例不包含任何这些,所以这可能是问题所在。

您还可以使用像 xmlstarlet formatxmllint --format 这样的工具来格式化/重新缩进 xml 文件。


更新:我做了一些更多的研究,看起来你想要做的事情对于 libxml2 是不可能的。引用 FAQ :

Libxml2 will not invent spaces in the content of a document since all spaces in the content of a document are significant. If you build a tree from the API and want indentation:

  1. the correct way is to generate those yourself too.
  2. the dangerous way is to ask libxml2 to add those blanks to your content …

话虽这么说,但我确实设法通过使用 xmlKeepBlanksDefault (0) 获得了正确的缩进输出。但是我并没有合并两个文档,我只是加载了一个并在其中插入了一些节点。因此,如果它对您不起作用,可能是因为您要合并的节点包含空格。所以你可以尝试在插入之前修剪。

如果您不发布您正在尝试做的事情的完整示例,则很难提供建议。

关于c++ - 使用 libxml2 缩进合并的 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41135319/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com