Thursday, February 21, 2013

xml handy items

I do a lot of processing of XML documents from various sources.  Just a couple of items I want to have around even through they are in my library of tricks. Removes declaration from XML document so that it can be loaded into XDocument. 

private Regex M_RemoveDecl = new Regex(@"<\?xml.*?\?>");

This is to remove namespaces in documents.  Makes the query of the document easier.
... Taken from this discussion


public static string RemoveAllNamespaces(string xmlDocument) { XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument)); return xmlDocumentWithoutNs.ToString(); } private static XElement RemoveAllNamespaces(XElement xmlDocument) { if (!xmlDocument.HasElements) { XElement xElement = new XElement(xmlDocument.Name.LocalName); xElement.Value = xmlDocument.Value; foreach (XAttribute attribute in xmlDocument.Attributes()) xElement.Add(attribute); return xElement; } return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); }

No comments:

Post a Comment