Merge XElement into XDocument and resolve namespaces

本小妞迷上赌 提交于 2019-12-31 03:36:07

问题


Given the following XDocument, initialized into variable xDoc:

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

I have a template embedded in an XML file (let's call it body.xml):

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

Which I would like to put as a child of <ReportSection>. Problem is if add it through XElement.Parse(body.xml), it keeps the namespace, even though I would think namespace should be removed (no point in duplicating itself - already declared on the parent). If I don't specify namespace, it puts an empty namespace instead, so it becomes <Body xmlns="">.

Is there a way to properly merge XElement into XDocument? I would like to get the following output after 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>

回答1:


I'm not sure why this is happening, but removing the xmlns attribute from the body element seems to work:

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


来源:https://stackoverflow.com/questions/13613917/merge-xelement-into-xdocument-and-resolve-namespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!