July 21, 2010

Quickly Add Xml To XmlDocument

This line loads an Xml document, looks for the presence of a particular line and if it is not there, adds it to the xml document. This is useful for updating a config file with a particular line of xml. Uses XPath to find the interesting element of the xml file.
public static void UpdateAnXmlNode(string xmlFileName)
{
  XmlDocument xDoc = new XmlDocument();
  try
  {
    // load the configuration file
    xDoc.Load(xmlFileName);

    // find the node of interest from the key
    XmlNode theNode =
    xDoc.SelectSingleNode(
@"/configuration/xxxConfiguration/moduleGroups/add[@trustName = 'Default']/modules");

    bool customXmlLinePresent = false;
    if (theNode != null)
    {
      customXmlLinePresent = theNode.InnerXml.Contains(
             "XXX.YYY.Sandbox.DebugTree.Module");
    }
    string extraXml = string.Empty;
    if (!customXmlLinePresent)
        extraXml += @"<add moduleType=""XXX.YYY.Sandbox.DebugTree.Module, XXX.YYY.Sandbox"" />" + Environment.NewLine;

    if (extraXml.Length > 0)
    {
      theNode.InnerXml += extraXml;
      xDoc.PreserveWhitespace = true;
      xDoc.Save(xmlFileName);
    }
  }
  catch (XmlException ex)
  {
    DoSomethingWithError(ex);
  }
}

No comments: