Friday, May 2, 2014

Write New or Existing XML in C#

Suppose i need to create XMLPath = @"c:\data\xmlfile.xml";


if (!File.Exists(XMLPath))
{
        //If XML File does not exist then Its creating XML from below method
        File.Create(XMLPath);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        using (XmlWriter writer = XmlWriter.Create(XMLPath, settings))
        {
                writer.WriteStartDocument();
                writer.WriteComment("This file is generated by My Custom Tool.");
                writer.WriteStartElement("root");
                        //This is for child nodes
                        writer.WriteStartElement("childnode");
                        writer.WriteAttributeString("name", GameName);
                        writer.WriteAttributeString("path", XMLPath); 
                        writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
        }
}
else
{
        XmlDocument doc = new XmlDocument();
        doc.Load(XMLPath);
        XmlNodeList rootNodeList = doc.GetElementsByTagName("childnode");
        //Now Checking If node already exist
        bool nodeFound = false;
        foreach (XmlNode nd in rootNodeList)
        {
                    if (nd.Attributes["name"].Value.ToLower() == GameName.ToLower())
                    {
                          nd.Attributes["path"].Value = XMLPath;
                          doc.Save(XMLPath);
                          nodeFound = true;
                    }
        }
        if (nodeFound) return;
        //If Node doesn't exist already then 
        XmlNode root = doc.DocumentElement;
        XmlElement elem = doc.CreateElement("childnode");
        XmlAttribute nameAttr = doc.CreateAttribute("name");
        XmlAttribute gameAttr = doc.CreateAttribute("path");
        nameAttr.Value = GameName;
        gameAttr.Value = XMLPath;
        elem.Attributes.Append(nameAttr);
        elem.Attributes.Append(gameAttr);
        package.InsertBefore(elem, root.FirstChild);
        doc.Save(XMLPath);
}

It will create XML like below

<root>
      <childnode name="1" path="somename.xml"/>
      <childnode name="2" path="someothername.xml"/>
</root>

No comments:

Post a Comment