Victorio Berra
Victorio Berra

Reputation: 3125

How do I remove the xmlns="" attribute added to newly created XElement nodes?

When I add new nodes to the root of a node that has a namespace defined, subsequent nodes added all receive xmlns="" attached to to them. This is the code that shows my problem:

void Main()
{
    var xdoc = new XDocument();
    var shipmentRoot = new XElement("{someNS}Shipment");

    var newElement = new XElement("ContainerCollection", new XElement("Container", new XElement("ContainerNumber", "42")));
    newElement.SetAttributeValue("Content", "Partial");

    shipmentRoot.Add(newElement);
    xdoc.Add(shipmentRoot);
    xdoc.Dump();

}

Generates this XML:

<Shipment xmlns="someNS">
  <ContainerCollection Content="Partial" xmlns="">
    <Container>
      <ContainerNumber>42</ContainerNumber>
    </Container>
  </ContainerCollection>
</Shipment>

My desired XML would be:

<Shipment xmlns="someNS">
  <ContainerCollection Content="Partial">
    <Container>
      <ContainerNumber>42</ContainerNumber>
    </Container>
  </ContainerCollection>
</Shipment>

Upvotes: 0

Views: 278

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503489

While I suspect this is a duplicate, I can't easily find it. The problem is that in your desired XML, the ContainerCollection, Container and ContainerNumber elements are in the namespace "someNS" as that is the default inherited from their Shipment ancestor... but you're creating elements with an empty namespace. The fix is just to create them with the right namespace:

// I prefer this over using {someNS}Shipment, personally. YMMV.
XNamespace ns = "someNS";
var shipmentRoot = new XElement(ns + "Shipment");

var newElement = new XElement(ns + "ContainerCollection",
     new XElement(ns + "Container",
         new XElement(ns + "ContainerNumber", "42")));
newElement.SetAttributeValue("Content", "Partial");

Upvotes: 1

Related Questions