[英]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.