【发布时间】:2012-12-13 17:14:43
【问题描述】:
我的 XML 结构类似于:
<root>
<SomeElement>
<AnotherElement>
<ElementIWant x="1" y="1"/>
</AnotherElement>
</SomeElement>
<SomeElement>
<AnotherElement>
<ElementIWant x="1" y="1"/>
<ElementIWant x="2" y="1"/>
<ElementIWant x="3" y="1"/>
</AnotherElement>
</SomeElement>
</root>
正在读入boost::property_tree,有1..Many<SomeElement>s,然后在该元素内的任意深度可能有1..Many <ElementIWant>s
有没有办法按照它们在文档中出现的顺序直接(在单个循环中)迭代 <ElementIWant>?
我看过equal_range
void iterateOverPoints()
{
const char* test =
"<?xml version=\"1.0\" encoding=\"utf-8\"?><root>"
"<SomeElement>"
"<AnotherElement>"
"<ElementIWant x=\"1\" y=\"1\"/>"
"</AnotherElement>"
"</SomeElement>"
"<SomeElement>"
"<AnotherElement>"
"<ElementIWant x=\"1\" y=\"1\"/>"
"<ElementIWant x=\"2\" y=\"1\"/>"
"<ElementIWant x=\"3\" y=\"1\"/>"
"</AnotherElement>"
"</SomeElement>"
"</root>";
boost::property_tree::ptree message;
std::istringstream toParse(test);
boost::property_tree::read_xml(toParse,result_tree);
//Now we need to locate the point elements and set the x/y accordingly.
std::pair< boost::property_tree::ptree::const_assoc_iterator,
boost::property_tree::ptree::const_assoc_iterator > result =
message.equal_range("ElementIWant");
for( boost::property_tree::ptree::const_assoc_iterator it = result.first;
it != result.second; ++it )
{
std::cout << it->first << " : ";
const boost::property_tree::ptree& x = it->second.get_child( "<xmlattr>.x" );
const boost::property_tree::ptree& y = it->second.get_child( "<xmlattr>.y" );
std::cout << x.get_value<int>() << "," << y.get_value<int>() << "\n";
}
return;
}
但是它似乎无法返回节点(我怀疑这是因为 equal_range 在提供的树节点级别上工作)这让我想到了上面的问题......
【问题讨论】:
-
你试过
equal_range("SomeElement.AnotherElement.ElementIWant");吗?不过,不确定当存在两个 SomeElement 副本时会发生什么。 -
过去的爆炸! @TreborRude 我认为当时它没有按照我想要的方式运行,或者它没有工作。也许从那时起图书馆已经得到了增强——但我现在远离那个代码领域。 :) 谢谢你的建议。
标签: c++ boost boost-propertytree