由于这是标记的C++,我假设您可以使用libxml ++库绑定.
我写了一个简单的程序:
DomParserfind()在文档根节点上使用XPath查询来获取属性.Attribute节点get_value()这是代码:
#include <iostream>
#include <libxml++/libxml++.h>
using namespace std;
using namespace Glib;
using namespace xmlpp;
int main(int argc, char* argv[])
{
// Parse the file
DomParser parser;
parser.parse_file("file.xml");
Node* rootNode = parser.get_document()->get_root_node();
// Xpath query
NodeSet result = rootNode->find("/root/a/b/@attr");
// Get first node from result
Node *firstNodeInResult = result.at(0);
// Cast to Attribute node (dynamic_cast on reference can throw [fail fast])
Attribute &attribute = dynamic_cast<Attribute&>(*firstNodeInResult);
// Get value of the attribute
ustring attributeValue = attribute.get_value();
// Print attribute value
cout << attributeValue << endl;
}
Run Code Online (Sandbox Code Playgroud)
鉴于此输入:
<!-- file.xml -->
<root>
<a>
<b attr="I want to get this"> </b>
</a>
</root>
Run Code Online (Sandbox Code Playgroud)
代码将输出:
I want to get this
Run Code Online (Sandbox Code Playgroud)
要在Unix系统上编译它:
c++ `pkg-config libxml++-2.6 --cflags` `pkg-config libxml++-2.6 --libs` file.cpp
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7166 次 |
| 最近记录: |