gpt4 book ai didi

c++ - RapidXML 使用先前的属性值访问单个属性值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:27:03 25 4
gpt4 key购买 nike

我在 PC 上的 VS2012 中使用 rapidXML 和 C++。我已经解析了 XML 文件,但现在我想单独打印出属性值。我通常可以使用下面的代码来做到这一点。但是,此方法需要知道节点名称和属性名称。这是一个问题,因为我有多个同名节点和多个同名属性。我的问题是,当节点名称和属性名称都不唯一时,如何获取单个属性值?

当我有一个唯一的节点名和属性名时我使用的代码:

xml_node<> *node0 = doc.first_node("NodeName"); //define the individual node you want to access
xml_attribute<> *attr = node0->first_attribute("price"); //define the individual attribute that you want to access
cout << "Node NodeName has attribute " << attr->name() << " ";
cout << "with value " << attr->value() << "\n";

我的 XML 测试文件:

<catalog>
<book>
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
</book>
<book>
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
</book>
</catalog>

对于这个具体示例,我如何获取第二本书的价格属性值?我可以输入标题属性值“Midnight Rain”并以某种方式使用它来获取下一个值吗?

最佳答案

您可以使用 next_sibling(const char *) 成员函数迭代兄弟节点,直到找到具有正确属性值的节点。我没有测试过以下代码,但它应该让您了解您需要做什么:

typedef rapidxml::xml_node<>      node_type;
typedef rapidxml::xml_attribute<> attribute_type;

/// find a child of a specific type for which the given attribute has
/// the given value...
node_type *find_child(
node_type *parent,
const std::string &type,
const std::string &attribute,
const std::string &value)
{
node_type *node = parent->first_node( type.c_str());
while (node)
{
attribute_type *attr = node->first_attribute( attribute.c_str());
if ( attr && value == attr->value()) return node;
node = node->next_sibling( type.c_str());
}
return node;
}

然后您可以通过调用找到第二本书:

node_type *midnight = find_child( doc, "book", "title", "Midnight Rain");

获得那本书的价格应该很容易。

一般来说,在处理 rapidxml 时,我倾向于创建许多这样的小辅助函数。我发现它们使我的代码在没有 xpath 函数的情况下更易于阅读...

关于c++ - RapidXML 使用先前的属性值访问单个属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17683231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com