C# 如何从 XElement 创建的节点中删除空的 xmlns 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12038636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:10:16  来源:igfitidea点击:

How can I remove empty xmlns attribute from node created by XElement

c#.netxmllinq-to-xml

提问by GrzesiekO

This is my code:

这是我的代码:

XElement itemsElement = new XElement("Items", string.Empty);
//some code
parentElement.Add(itemsElement);

After that I got this:

之后我得到了这个:

<Items xmlns=""></Items>

Parent element hasn't any namespace. What can I do, to get an Itemselement without the empty namespace attribute?

父元素没有任何命名空间。我该怎么做才能获得Items没有空命名空间属性的元素?

采纳答案by Christoffer Lette

It's all about how you handle your namespaces. The code below creates child items with different namespaces:

这完全取决于您如何处理您的命名空间。下面的代码创建具有不同命名空间的子项:

XNamespace defaultNs = "http://www.tempuri.org/default";
XNamespace otherNs = "http://www.tempuri.org/other";

var root = new XElement(defaultNs + "root");
root.Add(new XAttribute(XNamespace.Xmlns + "otherNs", otherNs));

var parent = new XElement(otherNs + "parent");
root.Add(parent);

var child1 = new XElement(otherNs + "child1");
parent.Add(child1);

var child2 = new XElement(defaultNs + "child2");
parent.Add(child2);

var child3 = new XElement("child3");
parent.Add(child3);

It will produce XML that looks like this:

它将生成如下所示的 XML:

<root xmlns:otherNs="http://www.tempuri.org/other" xmlns="http://www.tempuri.org/default">
    <otherNs:parent>
        <otherNs:child1 />
        <child2 />
        <child3 xmlns="" />
    </otherNs:parent>
</root>

Look at the difference between child1, child2and child3. child2is created using the default namespace, which is probably what you want, while child3is what you have now.

看看child1,child2和之间的区别child3child2是使用默认命名空间创建的,这可能是您想要的,而child3这正是您现在拥有的。