36

这是我的代码:

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

之后我得到了这个:

<Items xmlns=""></Items>

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

4

1 回答 1

85

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

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:

<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和之间的区别child3child2是使用默认命名空间创建的,这可能是您想要的,而child3这正是您现在所拥有的。

于 2012-08-20T14:18:50.627 回答