我有以下 xml,我正在尝试使用 LINQ to XML 从中删除所有“xmlns”属性:
<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>
使用以下代码。它为文档中的每个“xmlns”属性命中“attributesToRemove.Remove()”。但是当我保存文档时,我仍然拥有原始 XML。任何想法,可能是什么问题?
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();