Skip to content

Instantly share code, notes, and snippets.

@pwdonald
Created February 5, 2014 20:20
Show Gist options
  • Save pwdonald/8832237 to your computer and use it in GitHub Desktop.
Save pwdonald/8832237 to your computer and use it in GitHub Desktop.
C# Remove Null Fields from XML
// XML NULL FIELD REMOVAL
// Removes all Null fields (both with nil=true) from a XmlDoc
public static XmlDocument RemoveNullFields(this XmlDocument xmldoc)
{
XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
XmlNodeList nullFields = xmldoc.SelectNodes("//*[@xsi:nil='true']", mgr);
if (nullFields != null && nullFields.Count > 0)
{
for (int i = 0; i < nullFields.Count; i++)
{
nullFields[i].ParentNode.RemoveChild(nullFields[i]);
}
}
return xmldoc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment