如何在 PugiXML 中检查 XML 元素是否存在
在 PugiXML 中检查元素是否存在很简单:只需调用 bool(element) 或在 if 子句中直接使用元素:
pugixml_check_example.cpp
// 使用 bool(element) 的示例
cout << "<root-element> exists: " << std::boolalpha
<< bool(doc.child("root-element")) << endl;
cout << "<not-root-element> exists: " << std::boolalpha
<< bool(doc.child("not-root-element")) << endl;
// 在 if 子句中直接使用元素的示例
if(doc.child("root-element")) {
cout << "是的,<root-element> 存在!" << endl;
}完整示例:
pugixml_example.cpp
#include <iostream>
#include <pugixml.hpp>
using namespace std;
using namespace pugi;
int main() {
xml_document doc;
xml_parse_result result = doc.load_file("test.xml");
// 使用 bool(element) 的示例
cout << "<root-element> exists: " << std::boolalpha
<< bool(doc.child("root-element")) << endl;
cout << "<not-root-element> exists: " << std::boolalpha
<< bool(doc.child("not-root-element")) << endl;
// 在 if 子句中直接使用元素的示例
if(doc.child("root-element")) {
cout << "是的,<root-element> 存在!" << endl;
}
}CMakeLists.txt
add_executable(pugixml-example pugixml-example.cpp)
target_link_libraries(pugixml-example pugixml)test.xml
<?xml version="1.0" encoding="UTF-8"?>
<root-element>Test text</root-element>使用以下命令编译:
build_and_make.sh
cmake .
makeCheck out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow