nai*_*ikh 5 c# xml linq-to-xml xml-namespaces
在发布此问题之前,我已尝试堆栈上的所有其他解决方案,但没有成功.
我无法使用C#从XElement中删除空的xmlns属性,我尝试了以下代码.
XElement.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
Run Code Online (Sandbox Code Playgroud)
另一个在这里发帖
foreach (var attr in objXMl.Descendants().Attributes())
{
var elem = attr.Parent;
attr.Remove();
elem.Add(new XAttribute(attr.Name.LocalName, attr.Value));
}
Run Code Online (Sandbox Code Playgroud)
小智 12
Image这是你的xml文件
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
Run Code Online (Sandbox Code Playgroud)
这是你期望的
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
Run Code Online (Sandbox Code Playgroud)
我认为下面的代码就是你想要的.您需要将每个元素放入正确的命名空间,并删除受影响元素的任何xmlns =''属性.后一部分是必需的,否则LINQ to XML基本上试图给你留下一个元素
<!-- This would be invalid -->
<Firstelement xmlns="" xmlns="http://my.namespace">
Run Code Online (Sandbox Code Playgroud)
这是代码:
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(...)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7862 次 |
| 最近记录: |