Grz*_*ekO 33 .net c# xml linq-to-xml
这是我的代码:
XElement itemsElement = new XElement("Items", string.Empty);
//some code
parentElement.Add(itemsElement);
Run Code Online (Sandbox Code Playgroud)
之后我得到了这个:
<Items xmlns=""></Items>
Run Code Online (Sandbox Code Playgroud)
父元素没有任何名称空间.我该怎么做才能获得Items
没有空命名空间属性的元素?
Chr*_*tte 73
这都是关于如何处理命名空间的.下面的代码创建具有不同命名空间的子项:
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);
Run Code Online (Sandbox Code Playgroud)
它将生成如下所示的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>
Run Code Online (Sandbox Code Playgroud)
看看之间的区别child1
,child2
和child3
.child2
是使用默认命名空间创建的,这可能是您想要的,而child3
现在就是您所拥有的.