How to remove all namespaces from XML with C#?

前端 未结 30 2547
悲哀的现实
悲哀的现实 2020-11-22 13:30

I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like?

Defined interface:

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 13:43

    Simple solution that actually renames the elements in-place, not creating a copy, and does a pretty good job of replacing the attributes.

    public void RemoveAllNamespaces(ref XElement value)
    {
      List attributesToRemove = new List();
      foreach (void e_loopVariable in value.DescendantsAndSelf) {
        e = e_loopVariable;
        if (e.Name.Namespace != XNamespace.None) {
          e.Name = e.Name.LocalName;
        }
        foreach (void a_loopVariable in e.Attributes) {
          a = a_loopVariable;
          if (a.IsNamespaceDeclaration) {
            //do not keep it at all
            attributesToRemove.Add(a);
          } else if (a.Name.Namespace != XNamespace.None) {
            e.SetAttributeValue(a.Name.LocalName, a.Value);
            attributesToRemove.Add(a);
          }
        }
      }
      foreach (void a_loopVariable in attributesToRemove) {
        a = a_loopVariable;
        a.Remove();
      }
    }
    

    Note: this does not always preserve original attribute order, but I'm sure you could change it to do that pretty easily if it's important to you.

    Also note that this also could throw an exception, if you had an XElement attributes that are only unique with the namespace, like:

    
        
    
    

    which really seems like an inherent problem. But since the question indicated outputing a String, not an XElement, in this case you could have a solution that would output a valid String that was an invalid XElement.

    I also liked jocull's answer using a custom XmlWriter, but when I tried it, it did not work for me. Although it all looks correct, I couldn't tell if the XmlNoNamespaceWriter class had any effect at all; it definitely was not removing the namespaces as I wanted it to.

提交回复
热议问题