如何删除空的xmlns由的XElement创建的节点属性节点、属性、xmlns、XElement

2023-09-04 07:08:34 作者:最美流年

这是我的code:

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

在我得到这样的:

<Items xmlns=""></Items>

父元素还没有任何名称空间。我能做些什么,以获得产品无空命名空间属性的元素?

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

推荐答案

这是所有关于你如何处理你的命名空间。在code以下具有不同的命名空间创建子项:

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);

这将产生XML看起来像这样的:

It will produce XML that looks like this:

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

child1 的child2 之间的区别和 child3 的child2 使用默认的命名空间,这可能是你想要的,而 child3 是你现在有什么是创造。

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