# XmlParser模块 UE4(Unreal Engine 4)提供了一个名为XmlParser的模块,这是一个C++接口,用于解析XML文件。主要是通过一些类和方法,你可以读取,查询,操作和创建XML文档。以下是一些关键的类和方法: 1. **FXmlFile类**: 这个类表示一个XML文件。它包含一个XML文档的根节点(通过FXmlNode)。你可以使用FXmlFile类加载一个XML文件,然后查询和操作其内容。 - 构造函数: `FXmlFile(const FString& FilePath, EConstructMethod::Type ConstructMethod = EConstructMethod::CheckForErrors)`。通过给定的文件路径创建一个FXmlFile对象。可以选择是否检查错误。 - `IsValid()`: 如果XML文件有效(没有解析错误)返回true。 - `GetLastError()`: 如果有解析错误,返回描述错误的字符串。 - `GetRootNode()`: 返回文档的根FXmlNode。 2. **FXmlNode类**: 这个类表示一个XML节点。你可以通过FXmlNode访问节点的名称,属性,以及子节点。 - `GetTag()`: 返回节点的名称。 - `GetContent()`: 返回节点的内容。 - `GetAttribute(FString Name)`: 返回给定名称的属性值。如果属性不存在,返回空字符串。 - `GetChildrenNodes()`: 返回一个包含此节点所有子节点的数组。 3. **FXmlAttribute类**: 这个类表示一个XML属性,由名称和值组成。 - `GetTag()`: 返回属性的名称。 - `GetValue()`: 返回属性的值。 以下是一个简单的示例,展示了如何使用这些接口加载一个XML文件,并打印其所有节点的内容: ```cpp FXmlFile xmlFile(TEXT("path_to_your_xml_file.xml")); if (!xmlFile.IsValid()) { UE_LOG(LogTemp, Error, TEXT("XML File error: %s"), *xmlFile.GetLastError()); return; } FXmlNode* rootNode = xmlFile.GetRootNode(); PrintNodeRecursive(rootNode, 0); // Recursive function to print node information void PrintNodeRecursive(FXmlNode* node, int depth) { // Print the node tag and content with indentation based on depth FString indentation = FString::ChrN(depth, '\t'); UE_LOG(LogTemp, Log, TEXT("%sNode: %s, Content: %s"), *indentation, *node->GetTag(), *node->GetContent()); // Print all attributes for (auto& attr : node->GetAttributes()) { UE_LOG(LogTemp, Log, TEXT("%sAttribute: %s, Value: %s"), *indentation, *attr.GetTag(), *attr.GetValue()); } // Recursively print all child nodes for (auto* childNode : node->GetChildrenNodes()) { PrintNodeRecursive(childNode, depth + 1); } } ``` 注意:以上接口只适用于读取和查询XML文件,不适用于修改或创建新的XML文件。如果你需要修改或创建XML文件,你可能需要使用其他库,如tinyxml2等。 # 示例 XML文件 ```xml <?xml version="1.0" encoding="utf-8"?> <PlayerConfig> <PlayerData name="Ale" id="1001"></PlayerData> <Hp>9990</Hp> <Mp>190</Mp> </PlayerConfig> ``` 拿到根节点后的获取 ```cpp bool UMyPlayerConfigData::LoadDataWithXml(const FXmlNode* Node) { if(!Node) { return false; } for(const FXmlNode* ChildNode:Node->GetChildrenNodes()) { FString Tag = ChildNode->GetTag(); if(Tag == TEXT("PlayerData")) { this->Name = ChildNode->GetAttribute(TEXT("name")); this->Id = FCString::Atoi(*ChildNode->GetAttribute(TEXT("id"))); } else if(Tag == TEXT("Hp")) { this->Hp = FCString::Atoi(*ChildNode->GetContent()); }else if(Tag == TEXT("Mp")) { this->Mp = FCString::Atoi(*ChildNode->GetContent()); } } return true; } ```