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

前端 未结 1 639
旧时难觅i
旧时难觅i 2020-12-06 09:17

This is my code:

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

After that I g

相关标签:
1条回答
  • 2020-12-06 09:32

    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.

    0 讨论(0)
提交回复
热议问题