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();
    // load the configuration file

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

    bool customXmlLinePresent = false;
    if (theNode != null)
      customXmlLinePresent = theNode.InnerXml.Contains(
    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;
  catch (XmlException ex)

No comments: