如何删除xmlns =""属性是否已添加到新创建的XElement节点?

时间:2014-08-06 15:35:28

标签: c# xml linq-to-xml xelement

当我将新节点添加到定义了命名空间的节点的根节点时,后续节点添加了所有receive xmlns =""附在他们身上。这是显示我的问题的代码:

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();

}

生成此XML:

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

我想要的XML是:

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

1 个答案:

答案 0 :(得分:1)

虽然我怀疑这是重复的,但我不能轻易找到它。问题是,在您想要的XML中,ContainerCollectionContainerContainerNumber元素位于命名空间"someNS"中,因为这是从Shipment继承的默认值祖先......但您正在使用命名空间创建元素。修复只是使用正确的命名空间创建它们:

// 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");