Your approach is actually not too far off the mark, but you’re using the wrong getelement method. GetElementById searches for an attribute called ID, and then attempts to match the argument up against it. It returns null for you, because your XML doesn’t have any nodes with an ID attribute with a name corresponding to the rootNodeName.
Instead, use XmlDocument.GetElementsByTagName, see this link:
It returns a list of all elements whose tagname is what you provide, and since you mentioned that all your nodes have unique tag names, the returned array will always have length = 1 if the element already exists, and the node you want will always be at index = 0 if it exists. If the returned array has length = 0, it’s because the node doesn’t exist and you can go ahead and create it.
public void ReadXmlSettings()
{
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.Load("myXmlSettings.xml");
// Get the root element (which is "transforms" in your case).
System.Xml.XmlElement root = xmlDocument.DocumentElement;
// Get the Exterieur element or create it when does not exist.
System.Xml.XmlElement exterieurElement = this.GetChildByName(root, "Exterieur", xmlDocument);
// Get the Interieur element or create it when does not exist.
System.Xml.XmlElement interieurElement = this.GetChildByName(exterieurElement, "Interieur", xmlDocument);
// Do something with interieur element...
}
private System.Xml.XmlElement GetChildByName(System.Xml.XmlElement parent, string childName, System.Xml.XmlDocument xmlDocument)
{
// Try to find it in the parent element.
System.Xml.XmlElement childElement = parent.SelectSingleNode(childName) as System.Xml.XmlElement;
if (null == childElement)
{
// The child element does not exists, so create it.
childElement = xmlDocument.CreateElement(childName);
parent.AppendChild(childElement);
}
return childElement;
}
You have many ways to doing so. But if your goal is to get some "Settings" on the begining of your game, I really suggest you to look after the Serializer stuff.
All you need is a Class which describe your settings as "Properties" and add these line where you need to get the settings back from XML.
XmlSerializer serializer = new XmlSerializer(typeof(SettingsClass));
System.IO.FileStream fs = new System.IO.FileStream(xmlPath, System.IO.FileMode.Open);
SettingsClass settings = (SettingsClass)serializer.Deserialize(fs);
If you want to create the xml based on the class :
SettingsClass settings = new SettingsClass();
XmlSerializer serializer = new XmlSerializer(typeof(SettingsClass));
System.IO.FileStream fs = new System.IO.FileStream(xmlPath, System.IO.FileMode.Create);
serializer.Serialize(fs, settings);
I don't know if it's a correct solution for your case, but it seams to me a more developper friendly way to get some settings saved.