Changing an XmlDocument

In the previous example, you didn’t actually change the underlying document. In fact, there’s nothing there that you couldn’t have done with an XmlReader. Unlike an XmlReader, however, the DOM allows you to change an existing XML document.

Suppose you decided to stop validating the inventory records. In order to make this change, you would need to remove the DOCTYPE node from all of the XML files. How would you go about doing this?

The short answer is XmlNode.RemoveChild( ). This method removes the node passed in from the object tree. You can read in all the XML files in the current directory, and remove the XmlDocumentType node. Then you can serialize the file back out (with the extension .new so you don’t overwrite the original) and check that the DOCTYPE node is gone:

string currentDirectory = Environment.CurrentDirectory;
string [ ] files = Directory.GetFiles(currentDirectory, "*.xml");

foreach (string file in files) {
  XmlDocument document = new XmlDocument( );
  document.Load(file);
  XmlDocumentType documentType = document.DocumentType;
  document.RemoveChild(documentType);
  document.Save(file + ".new");
}

This process can be repeated with any type of XmlNode. For example, you could remove the inventory element, leaving an empty document, except for the XML declaration. Or you could use RemoveAll( ) to remove everything in the document entirely, while leaving the empty file in place:

document.Load(file);
document.RemoveAll( );

Tip

If you remove the document ...

Get .NET & XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.