0

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>
Victorio Berra
  • 2,760
  • 2
  • 28
  • 53
  • Just create the elements in the `someNS` namespace. I'm sure this is a duplicate... – Jon Skeet Aug 06 '14 at 15:36
  • Your desired output indicates all elements should be in `someNS` - to do this, you'll need to add `ContainerCollection`, `Container` et al to `someNs` as well? – StuartLC Aug 06 '14 at 15:38

1 Answers1

1

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");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This is what I needed. After further searching I found the duplicate: http://stackoverflow.com/questions/8822859/remove-empty-xmlns-created-by-serializer – Victorio Berra Aug 06 '14 at 15:40
  • @VictorioBerra: Well that's talking about the XML serializer - not really a duplicate, IMO. I'm sure there are others though :) – Jon Skeet Aug 06 '14 at 15:41
  • 1
    I will say after implementing this solution it sucks to have to add ns + to every single one of my nodes. – Victorio Berra Aug 06 '14 at 15:49
  • You don't need to set the "Content" attribute separately. You can pass an XAttribute in the functional construction. – an phu Jun 15 '15 at 18:24
  • @anphu: Sure, but I was implementing a minimal change to the OP's original code. – Jon Skeet Jun 15 '15 at 18:41