tinyxml解析xml代码
时间: 2023-11-12 17:26:51 浏览: 45
以下是使用 TinyXML 解析 XML 的示例代码:
```c++
#include <iostream>
#include "tinyxml.h"
int main()
{
TiXmlDocument doc("example.xml"); // 加载 XML 文件
bool loadOkay = doc.LoadFile(); // 解析 XML 文件
if (loadOkay)
{
TiXmlElement* root = doc.RootElement(); // 获取根元素
// 遍历根元素下的所有子元素
for (TiXmlElement* elem = root->FirstChildElement(); elem != nullptr; elem = elem->NextSiblingElement())
{
std::cout << "Element name: " << elem->Value() << std::endl;
// 遍历当前子元素下的所有属性
for (TiXmlAttribute* attr = elem->FirstAttribute(); attr != nullptr; attr = attr->Next())
{
std::cout << "Attribute name: " << attr->Name() << ", Attribute value: " << attr->Value() << std::endl;
}
// 输出当前子元素的文本内容
std::cout << "Element text: " << elem->GetText() << std::endl;
}
}
else
{
std::cout << "Failed to load file" << std::endl;
}
return 0;
}
```
其中,example.xml 是要解析的 XML 文件的文件名。在代码中,我们首先通过 `TiXmlDocument` 类加载 XML 文件,然后通过 `RootElement()` 方法获取根元素,再通过 `FirstChildElement()` 和 `NextSiblingElement()` 方法遍历所有子元素。对于每一个子元素,我们可以通过 `Value()` 方法获取其名称,通过 `FirstAttribute()` 和 `Next()` 方法遍历其所有属性,通过 `GetText()` 方法获取其文本内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)