Prevent duplicate pugixml::xml_node

↘锁芯ラ 提交于 2020-01-05 10:24:14

问题


I'm writing a part of my app that store settings in XML file, but I don't want to 'client' duplicate, I want this:

<jack>
  <client name="something">
    <port name="someport" />
    <port name="someport_2" />
  </client>
</jack>

But instead I get:

<jack>
  <client name="something">
    <port name="someport" />
  </client>
  <client name="something">
    <port name="someport_2" />
  </client>
</jack>

thought "just check if node already exists" but that's the problem, so I've this piece of code:

// xjack is the root node
pugi::xml_node xclient = xjack.child(sclient.c_str());
if (!xclient) {
    xclient = xjack.append_child("client");
}

but !xclient always evaluate to true, tried also if (xclient.empty()) but not work also.


回答1:


thinking about the comments zeuxcg I could figure out what was wrong.

pugi::xml_node xclient = xjack.child(sclient.c_str()); is looking up for a child with name "something" that really doesn't exists, what I'm looking for is a tag with name "client" and attribute "name" with value of "something".

So, the correct is:

pugi::xml_node xclient = xjack.find_child_by_attribute("client", "name", sclient.c_str());
if (!xclient) {
    xclient = xjack.append_child("client");
    xclient.append_attribute("name").set_value(sclient.c_str());
}


来源:https://stackoverflow.com/questions/17355024/prevent-duplicate-pugixmlxml-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!