如何使用 xpath 使用 libxml2 从 C++ 中的 xml 文件中检索节点和特定元素字符串?
How to retrieve node and particular element string from xml file in C++ using libxml2 by using xpath?
如何使用 libxml 在 C++ 中检索文本值?
这里是 XML:
<?xml version="1.0" encoding="UTF-8"?>
<Help xmlns="http://www.example.org/HelpFileStructure" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/HelpFileStructure HelpFileStructure.xsd ">
<Text>dfgdfg</Text>
</Help>
代码:
void Help::HelpName()
{
string Help_text;
parser.parse_file(XmlFileName);
Node* root = parser.get_document()->get_root_node();
NodeSet result = root->find("/Help/Text");
Element *first_element = (Element *)result.at(0);
Help_text = first_element->get_child_text()->get_content();
}
使用这个:
NodeSet result = root->find("//*[local-name()='Help']/*[local-name()='Text']");
这会得到一个节点集,其中每个节点都是一个名为 Text
的元素,无论该元素位于什么名称空间中,它都是任何名为 Help
的元素的子元素,无论它是什么名称空间英寸
如果您只想要 http://www.example.org/HelpFileStructure
命名空间中的 Help
和 Text
元素,并且想要忽略文档可能包含的任何 Text
和 Help
元素如果它们在其他命名空间中,那么您可以像这样使用 namespace-uri()
函数:
NodeSet result = root->find("//*[local-name()='Help' and namespace-uri()='http://www.example.org/HelpFileStructure']/*[local-name()='Text' and namespace-uri()='http://www.example.org/HelpFileStructure']");
如何使用 libxml 在 C++ 中检索文本值?
这里是 XML:
<?xml version="1.0" encoding="UTF-8"?>
<Help xmlns="http://www.example.org/HelpFileStructure" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/HelpFileStructure HelpFileStructure.xsd ">
<Text>dfgdfg</Text>
</Help>
代码:
void Help::HelpName()
{
string Help_text;
parser.parse_file(XmlFileName);
Node* root = parser.get_document()->get_root_node();
NodeSet result = root->find("/Help/Text");
Element *first_element = (Element *)result.at(0);
Help_text = first_element->get_child_text()->get_content();
}
使用这个:
NodeSet result = root->find("//*[local-name()='Help']/*[local-name()='Text']");
这会得到一个节点集,其中每个节点都是一个名为 Text
的元素,无论该元素位于什么名称空间中,它都是任何名为 Help
的元素的子元素,无论它是什么名称空间英寸
如果您只想要 http://www.example.org/HelpFileStructure
命名空间中的 Help
和 Text
元素,并且想要忽略文档可能包含的任何 Text
和 Help
元素如果它们在其他命名空间中,那么您可以像这样使用 namespace-uri()
函数:
NodeSet result = root->find("//*[local-name()='Help' and namespace-uri()='http://www.example.org/HelpFileStructure']/*[local-name()='Text' and namespace-uri()='http://www.example.org/HelpFileStructure']");