Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

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

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 Items element without the empty namespace attribute?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<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, child2 and child3. child2 is created using the default namespace, which is probably what you want, while child3 is what you have now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...