-->

合并的XElement到的XDocument和解决命名空间(Merge XElement into

2019-08-03 06:53发布

鉴于以下XDocument ,初始化为变量xDoc

<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition">
  <ReportSection>
    <Width />
    <Page>
  </ReportSections>
</Report>

我有嵌入在一个XML文件的模板(我们称之为body.xml ):

<Body xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition">
  <ReportItems />        
  <Height />
  <Style />
</Body>

这也是我喜欢把为孩子<ReportSection> 问题是,如果添加它通过XElement.Parse(body.xml)它使命名空间,即使我想命名空间应该被删除(不点在重复自己-已经宣布对父)。 如果我不指定命名空间,它把一个空的命名空间,而不是,因此它成为<Body xmlns="">

有没有一种方法可以正确合并XElementXDocument ? 我想以后得到下面的输出xDoc.Root.Element("ReportSection").AddFirst(XElement)

<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition">
  <ReportSection>
    <Body>
      <ReportItems />        
      <Height />
      <Style />
    </Body>
    <Width />
    <Page>
  </ReportSections>
</Report>

Answer 1:

我不知道为什么发生这种情况,但在取出xmlns属性从body元素似乎工作:

var report = XDocument.Parse(
@"<Report xmlns=""http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"">
  <ReportSection>
    <Width />
    <Page />
  </ReportSection>
</Report>");

var body = XElement.Parse(
@"<Body xmlns=""http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"">
  <ReportItems />        
  <Height />
  <Style />
</Body>");

XNamespace ns = report.Root.Name.Namespace;
if (body.GetDefaultNamespace() == ns)
{
   body.Attribute("xmlns").Remove();
}

var node = report.Root.Element(ns + "ReportSection");
node.AddFirst(body);


文章来源: Merge XElement into XDocument and resolve namespaces