[英]Unable to remove empty xmlns attribute from XElement using c#
在发布这个问题之前,我已经尝试了堆栈上的所有其他解决方案,但没有成功。
我无法使用 C# 从 XElement 中删除空的 xmlns 属性,我尝试了以下代码。
XElement.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
另一张贴在这里
foreach (var attr in objXMl.Descendants().Attributes())
{
var elem = attr.Parent;
attr.Remove();
elem.Add(new XAttribute(attr.Name.LocalName, attr.Value));
}
Image 这是你的xml文件
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
这是你期待的
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
我认为下面的代码就是你想要的。 您需要将每个元素放入正确的命名空间,并删除受影响元素的所有 xmlns='' 属性。 后一部分是必需的,否则 LINQ to XML 基本上试图给你留下一个元素
<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">
这是代码:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml");
foreach (var node in doc.Root.Descendants())
{
// If we have an empty namespace...
if (node.Name.NamespaceName == "")
{
// Remove the xmlns='' attribute. Note the use of
// Attributes rather than Attribute, in case the
// attribute doesn't exist (which it might not if we'd
// created the document "manually" instead of loading
// it from a file.)
node.Attributes("xmlns").Remove();
// Inherit the parent namespace instead
node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
}
}
Console.WriteLine(doc); // Or doc.Save(...)
}
}
如果将父元素的命名空间添加到元素,则空命名空间标记将消失,因为它不是必需的,因为该元素位于同一命名空间中。
您是否尝试通过值获取 Xelement.Attribute 以在删除之前查看元素是否为“xmlns”。
Xelement.Attribute("xmlns").Value
这是一个更简单的方法来做到这一点。 我相信当您创建单独的 xml 段然后将它们加入您的文档时会发生这种情况。
xDoc.Root.SaveDocument(savePath);
private static void SaveDocument(this XElement doc, string filePath)
{
foreach (var node in doc.Descendants())
{
if (node.Name.NamespaceName == "")
{
node.Name = ns + node.Name.LocalName;
}
}
using (var xw = XmlWriter.Create(filePath, new XmlWriterSettings
{
//OmitXmlDeclaration = true,
//Indent = true,
NamespaceHandling = NamespaceHandling.OmitDuplicates
}))
{
doc.Save(xw);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.