使用 libxml2 缩进合并的 xml 文件

Indenting a merged xml file with libxml2

我正在尝试使用 libxml2 和 c++ 合并两个 xml 文件。
这些 xml 文件具有相同的架构但具有不同的内容,我需要将一些元素合并到主 xml 文件中。 这些 xml 个文件有不同的缩进。 (一个有 space 但另一个有标签)

这是我的伪代码:

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' 元素应该有相同的缩进。

如何才能很好地缩进合并后的文件? 提前致谢。

文档说:"Note that format = 1 provide node indenting only if xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was called."

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

您也可以使用 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) 获得了正确的缩进输出。但是我并没有合并两个文档,我只是加载了一个并在其中插入了一些节点。因此,如果它对您不起作用,可能是因为您要合并的节点包含空格。所以你可以尝试在插入之前修剪。

当您没有post您正在尝试做的事情的完整示例时,很难给出建议。