Remove attributes from XElement
Asked Answered
K

4

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?

Killigrew answered 7/7, 2014 at 10:38 Comment(1)
related: #987635Understrapper
O
9

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

Olsen answered 7/7, 2014 at 10:41 Comment(0)
H
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

Hussite answered 7/7, 2014 at 10:41 Comment(0)
B
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>
Blockhead answered 7/7, 2014 at 10:41 Comment(0)
M
0

Cleaner way.

  1. Declare an extension method :

     public static void RemoveXmlAttributes(this XElement xDocument)
     {
         xDocument.RemoveAttributes();
         foreach (XElement xmlChild in xDocument.Elements())
         {
             xmlChild.RemoveXmlAttributes();
         }
     }
    
  2. Then call it :

         XElement xml = XElement.Load(completionXml);
         xml.RemoveXmlAttributes();
    

The same can be done for XmlElement (instead of XElement)

Madaih answered 15/9, 2023 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.