Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
GrzesiekO Avatar asked Aug 20 '12 13:08

GrzesiekO


People also ask

How do I get rid of xmlns?

Open the map in the Design Studio. Edit the output card in question (in this case output card 1 of the validationMap map) and expand it so you can right click on Property > Schema > Type > Metadata > Name Spaces > http://www.example.com/IPO. After right clicking on http://www.example.com/IPO, left click on Delete.

What is the xmlns attribute?

the xmlns attribute specifies the xml namespace for a document. This basically helps to avoid namespace conflicts between different xml documents, if for instance a developer mixes xml documents from different xml applications.


1 Answers

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.

like image 106
Christoffer Lette Avatar answered Oct 13 '22 22:10

Christoffer Lette