使用 Boost property_tree 更新 XML 文件
我有以下 XML 文件:
<xml version="1.0" encoding="utf-8"?> <Data> <Parameter1>1</Parameter1> </Data>
我想添加一个新节点: Parameter2="2" 到数据节点。这段代码不起作用,保存的文件仍然只包含一个参数:
boost::property_tree::ptree tree; boost::property_tree::ptree dataTree; read_xml("test.xml", tree); dataTree = tree.get_child("Data"); dataTree.put("Parameter2", "2"); boost::property_tree::xml_writer_settings w(' ', 4); write_xml("test.xml", tree, std::locale(), w);
如果我在 dataTree.put 之后添加这两行,我会得到正确的结果:
tree.clear(); tree.add_child("Data", dataTree);
我不喜欢这个解决方案,因为它会产生更复杂的树结构问题。是否可以在不删除/添加子节点的情况下更新属性树?
I have the following XML file:
<xml version="1.0" encoding="utf-8"?> <Data> <Parameter1>1</Parameter1> </Data>
I want to add a new node: Parameter2="2" to the Data node. This code doesn't work, saved file still contains only one parameter:
boost::property_tree::ptree tree; boost::property_tree::ptree dataTree; read_xml("test.xml", tree); dataTree = tree.get_child("Data"); dataTree.put("Parameter2", "2"); boost::property_tree::xml_writer_settings w(' ', 4); write_xml("test.xml", tree, std::locale(), w);
If I add these two lines after dataTree.put, I get correct result:
tree.clear(); tree.add_child("Data", dataTree);
I don't like this solution, because it creates problems with more complicated tree structutes. Is it possible to update property tree without deleting/adding child nodes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码几乎是正确的,这是更新子节点的正确方法。
然而,有一个小错误。当您键入时:
您将“子”的副本分配给dataTree。因此,下一行指的是副本而不是您的层次结构。你应该写:
这样你就获得了对孩子的引用。
完整的例子是:
Your code is almost right, that is the right way to update a child node.
However, there is a small bug. When you type:
You assign to dataTree a copy of the "child". So, the next line refers to the copy and not to your hierarchy. You should write:
So you obtain a reference to the child.
The complete example is: