boost 属性树使用 write_xml() 添加空行

问题描述

我正在使用 boost(版本 1.70.0)属性树。如果我有这个 XML(没有空行):

<Root>
  <SomeOtherElement>..</SomeOtherElement>
  <Collection>
     <Item Attr1=".." attr2="" />
     <Item Attr1=".." attr2="" />
  </Collection>
</Root>

然后我提取一个节点,插入到另一个(空)树中:

auto node = pt.get_child("Root.Collection");
ptree new_pt{};
new_pt.put_child("Collection",node);
std::ostringstream os;
write_xml(os,new_pt);
auto xml = os.str();

我会得到带有空行的输出,如下所示:

  <Collection>



     <Item Attr1=".." attr2="" />
     <Item Attr1=".." attr2="" />
  </Collection>

我尝试了不同的东西。我可以通过迭代 Item 元素并一一添加来修复它。然后它就可以工作了,没有多余的行。但是,如果 Item 元素本身有一个子元素,那么它又会添加一堆空行。

解决方法

我认为它与这个重复,或者它只是属性树中的一个错误。

https://stackoverflow.com/a/6614372/1292791

使用修剪标志读取将解决问题:

pt::read_xml(filename,tree,boost::property_tree::xml_parser::trim_whitespace);

以漂亮的格式书写:

pt::write_xml(os,boost::property_tree::xml_writer_make_settings<std::string>(' ',1));