So I’m trying to read some information from a XML document using the FXmlFile API, the problem is that the GetRootNode keeps returning nullptr, which is behaviour I have come to understand is only supposed to happen when creating a XML file from buffer, which is not what I’m doing here. Does any body know what I’m doing wrong?
#include "XMLtest.h"
#include "Runtime/XmlParser/Public/XmlParser.h"
#include "Runtime/XmlParser/Public/XmlFile.h"
// Sets default values
AXMLtest::AXMLtest()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
FString AXMLtest::GetItemNameByID(int ItemId)
{
// Importing the .xml file with item database for parsing.
FXmlFile* ItemsDatabase = new FXmlFile("test.xml", EConstructMethod::ConstructFromFile);
// Quick check to see if the XML file object is valid.
if (ItemsDatabase->IsValid())
{
return FString(TEXT("Database file is not valid"));
}
// Getting root node from item database XML sheet, (should be <database>).
FXmlNode* DatabaseRoot = ItemsDatabase->GetRootNode();
// Quick check to see if the XML file object has a valid root node.
if (DatabaseRoot == nullptr)
{
return FString(TEXT("Database root node is not valid"));
}
// Converting the given ID to a Fstring so we can use it to search for its corresponding FXmlNode.
FString ItemIdString = FString(TEXT("ID-")) + FString::FromInt(ItemId);
FXmlNode* ItemNode = DatabaseRoot->FindChildNode(ItemIdString);
// Quick check to see if the item id has produced a valid FXmlNode object.
if (ItemNode == nullptr)
{
return FString(TEXT("No item with this Id found in the database"));
}
// Getting the item name from the ItemNode and returning it to the blueprint.
FString ItemName = ItemNode->FindChildNode(FString(TEXT("title")))->GetContent();
return ItemName;
}
This is what my XML file looks like:
<?xml version="1.0" encoding="utf-8"?>
<root>
<ID-0>
<title>apple</title>
</ID-0>
<ID-1>
<title>redapple</title>
</ID-1>
</root>
While we’re at it I’d also like to know if it is really necessary to name the root node ‘root’, because I’d prefer to call it something else for readability’s sake. Thanks in advance!