zos*_*sim 2 c# linq-to-xml xml-namespaces
我有现有的xml文档.
例如
<Test>
<A />
</Test>
Run Code Online (Sandbox Code Playgroud)
我将此xml加载到XDocument中.我需要将属性xmlns添加到此文档并使用此属性保存它.
var xml = new XDocument.Load("c:\\filePath.xml");
Run Code Online (Sandbox Code Playgroud)
我在尝试这个时:
xml.Root.SetAttributeValue("xmlns", "http://namespaceuri");
Run Code Online (Sandbox Code Playgroud)
我得到例外:
System.Xml.XmlException: The prefix '' cannot be redefined from 'http://namespaceuri' to within the same start element tag.
Run Code Online (Sandbox Code Playgroud)
谢谢
您还需要将名称设置为名称空间:
XNamespace ns = "http://namespaceuri";
foreach (var element in xml.Descendants().ToList())
{
element.Name = ns + element.Name.LocalName;
}
xml.Root.SetAttributeValue("xmlns", ns.ToString());
Run Code Online (Sandbox Code Playgroud)
基本上,您正在尝试将所有元素移动到该命名空间,并使其成为根元素的默认命名空间.您不能更改默认命名空间,同时将元素本身保留在不同但不合格的命名空间中.
将上面的代码与示例XML(固定为关闭A
)一起使用最终得到:
<Test xmlns="http://namespaceuri">
<A />
</Test>
Run Code Online (Sandbox Code Playgroud)
请注意,此代码将更改所有元素的命名空间.如果你想要更有选择性,你应该在Where
通话后添加一个xml.Descendants()
电话,例如
foreach (var element in xml.Descendants()
.Where(x => x.Name.Namespace == XNamespace.None)
.ToList())
Run Code Online (Sandbox Code Playgroud)