I’m trying to add new elements to my XML file in which I store strings. The user can look up these strings in a search panel, but also can add a new element if it’s not in the list.
I’ve tried adding a String but it doesn’t seem to be working. Here’s the code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE Activites [
<!ATTLIST activityData id ID #REQUIRED>
]>
<Activities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<activityData id="Aerobics">
<Activity_Description>Aerobics</Activity_Description>
</activityData>
</Activities>
This is just the basic XML file, there could be more information added to it in the future. The idea is to add new activityData to the XML file and save that file overwriting the original file.
Yes, almost correct. You tried to add ‘elmNew’ to the root of the xml document, but this is prohibited. You should before get an element where you want to place ‘elmNew’ and append ‘elmNew’ to it.
I don’t test, but finil code should e like this:
public void AddActivity(string act)
{
Debug.Log ("Adding activity to XML");
XmlElement elmNew = AXML.CreateElement("activityData");
XmlElement elmDesc = AXML.CreateElement("Activity_Description");
elmDesc.InnerText = act;
XmlElement elem = AXML.GetElementById("Aerobics"); // or you can use GetElementsByTagName(String) method
elem.AppendChild(elmNew);
elem.AppendChild(elmDesc);
AXML.Save(Application.persistentDataPath + "/" + "XML" + "/ActivitiesDatabase.xml");
}
public void AddActivity(string act)
{
string temp = char.ToUpper(act[0]) + act.Substring(1); //Sets the first char in the string to Upper case
searchFor = temp;
foundActivities = ReadActivitiesNode("Activities/activityData/Activity_Description");
if(!foundActivities.Contains(temp))
{
Debug.Log ("No activity found! Adding activity to XML");
XmlElement root = AXML.DocumentElement;
XmlElement elmNew = AXML.CreateElement("activtyData");
XmlElement elmDesc = AXML.CreateElement("Activity_Description");
elmNew.SetAttribute("id", temp);
elmDesc.InnerText = temp;
root.AppendChild(elmNew);
elmNew.AppendChild(elmDesc);
AXML.Save(Application.persistentDataPath + "/" + "XML" + "/ActivitiesDatabase.xml");
}
else
{
Debug.Log ("Activity already exists!");
}
}
Edit:
There seems to be one problem now. The XML is created and the new activitydata is added. But when i’m searching for it, there’s no item with the name added to the XML seems like the XML is not reloaded.
I’ve added this code but that doesn’t seem to work:
Which basically just reloads the XML to the AXML variable. But this doesn’t seem to work. Also when I restart the app the added string still isn’t findable.
Edit2:
The only thing i’m thinking of what can cause this, is that the XML is not sorted because the node will be added at the end of the root element.
Is there a way to simply sort an XML file?