I have the following xml, from which I am trying to remove all “xmlns” attributes using LINQ to XML:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<LinearLayout xmlns="clr-namespace:AndroidAssembly;assembly=AndroidAssembly"/>
<TextView xmlns="clr-namespace:AndroidAssembly;assembly=AndroidAssembly">
</StackPanel>
</Window>
The following code is used. It hits “attributesToRemove.Remove()” for each “xmlns” attribute in the document. But when I save the document, I still have the original XML. Any idea, what is the problem might be?
var sr = new StringReader(richTextBoxOriginalXml.Text);
XDocument xdoc = XDocument.Load(sr);
foreach(var node in xdoc.Descendants().ToList())
{
var xmlns = node.Attributes().FirstOrDefault(a => a.Name == "xmlns");
if (xmlns !=null)
{
var attributesToRemove = node.Attributes("xmlns").ToList();
attributesToRemove.Remove();
}
}
var writer = new StringWriter();
var xmlWriter = new XmlTextWriter(writer);
xmlWriter.Formatting = Formatting.Indented;
xdoc.WriteTo(xmlWriter);
richTextBoxTransformed.Text = writer.GetStringBuilder().ToString();
Like Marc Gravell pointed out before I posted,
xmlnsattribute (unqualified) is not an attribute as such, it’s considered part of the name of the element.StackPaneltag has no attributes here. It’s name, however, is{http://schemas.microsoft.com/winfx/2006/xaml/presentation}StackPanel.Name.Namespaceis{http://schemas.microsoft.com/winfx/2006/xaml/presentation}(XNamespacetype) andName.LocalName == "StackPanel".Thus you need to effectively rename the element. It should work.
Oversimplified (but compilable) program:
Output:
The difference in the
StackPanelelement is easy to notice…By the way, there is a typo in the XML you posted (
TextViewtag is not closed), but I can’t edit it out – edits must be at least 6 characters long 🙂 (Why 6?)