5

Please consider this XElement:

<MySerializeClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <F1>1</F1>
    <F2>2</F2>
    <F3>nima</F3>
</MySerializeClass>

I want to delete xmlns:xsi and xmlns:xsd from above XML. I wrote this code but it does not work:

 XAttribute attr = xml.Attribute("xmlns:xsi");
 attr.Remove();

I got this error:

Additional information: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

How I can delete above attributes?

Arian
  • 12,793
  • 66
  • 176
  • 300

3 Answers3

9

I would use xml.Attributes().Where(a => a.IsNamespaceDeclaration).Remove(). Or use xml.Attribute(XNamespace.Xmlns + "xsi").Remove().

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
2

you can try the following

//here I suppose that I'm loading your Xelement from a file :)
 var xml = XElement.Load("tst.xml"); 
 xml.RemoveAttributes();

from MSDN Removes the attributes of this XElement

BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
0

If you want to use namespaces, LINQ to XML makes that really easy:

xml.Attribute(XNamespace.Xmlns + "xsi").Remove();

here final clean and universal C# solution for removing all XML namespaces:

public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XDocument.Load(xmlDocument).Root);

    return xmlDocumentWithoutNs.ToString();
}

//Core recursion function
 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)));
    }

Output

 <MySerializeClass>
  <F1>1</F1> 
  <F2>2</F2> 
  <F3>nima</F3> 
 </MySerializeClass>
MRebai
  • 5,344
  • 3
  • 33
  • 52