Click here to Skip to main content
15,436,489 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi All,

I need to remove all namespaces from an xml file. I am using the functions

C#
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)));
}


The problem is that I am getting the following error being returned by one of the functions

{System.Xml.XmlException: The prefix '' cannot be redefined from '' to 'http://sample.response.power.core.com' within the same start element tag.
   at System.Xml.XmlWellFormedWriter.PushNamespaceExplicit(String prefix, String ns)
   at System.Xml.XmlWellFormedWriter.WriteEndAttribute()
   at System.Xml.Linq.ElementWriter.WriteStartElement(XElement e)
   at System.Xml.Linq.ElementWriter.WriteElement(XElement e)
   at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
   at System.Xml.Linq.XNode.GetXmlString(SaveOptions o)
   at System.Xml.Linq.XNode.ToString()


Can somebody thing of an alternative way of removing namespaces within an xml file?

Many thanks

bekets

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 21-Oct-12 2:52am
v2

 
Share this answer
 
v2
C#
static XElement stripNS(XElement root)
        {
            return new XElement(
                root.Name.LocalName,
                root.HasElements ?
                    root.Elements().Select(el => stripNS(el)) :
                    (object)root.Value
            );
        }


will remove all namespaces. Thanks ProgramFox for the pointer
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900