LINQ to XML - Load node then add to Xdocument - Namespace issue

时间:2016-06-10 16:18:19

标签: c# .net xml linq xml-namespaces

I am having serious trouble adding an XElement after loading that inherits the parent's namespace... I've tried multiple examples, set the exact same namespaces in both documents, tried removing the namespaces... this is honestly a mess, the only example I found was re-creating the XElement object with a namespace in the constructor but my XML is pretty massive. I do not wish to do this. Is there a way to Inherit namespaces after a load then add to parent (see code for example of what I mean).

xml = XDocument.Load(rdlFile);
var selectNode = xml.AssumeISelectedTheNodeIWantWithLinq();
//A static element loaded from a separate file
XElement elementNeedsNameSpace = XElement.Load("element.xml");
selectNode.Add(elementNeedsNameSpace );

//Output xml:
<MyAddedNode xmlns="">
  <AssumeLotsOfChilds>
    <SubChilds/>
  </AssumeLotsOfChilds>
</MyAddedNode>

//Root xml
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

If I remove the attribute then I get all the children messed up and receive the stupid xlmns="" :(

1 个答案:

答案 0 :(得分:1)

您的&#39;元素从单独的文件加载&#39;并且孩子没有命名空间,因此当他们被插入到具有不同默认命名空间的文档中时添加xmlns=""

如果要删除该属性,则需要更改所有元素名称以使用要插入的文档的默认命名空间:

XNamespace ns = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"

foreach (var element in elementNeedsNamespace.DescendantsAndSelf())
{
     element.Name = ns + element.Name.LocalName;
}

selectNode.Add(elementNeedsNameSpace);