将XElement合并到XDocument中并解析名称空间 [英] Merge XElement into XDocument and resolve namespaces
问题描述
给出以下XDocument
,并将其初始化为变量xDoc
:
Given the following XDocument
, initialized into variable xDoc
:
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition">
<ReportSection>
<Width />
<Page>
</ReportSections>
</Report>
我在XML文件中嵌入了一个模板(我们称之为body.xml
):
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>
我想把它作为<ReportSection>
的子代.问题是,如果通过XElement.Parse(body.xml)
将其添加,即使我认为应删除名称空间(复制自身也没有意义-已在父级上声明),它仍保留名称空间.如果我未指定名称空间,则会放置一个空的名称空间,因此它将变为<Body xmlns="">
.
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="">
.
是否可以将XElement
正确合并到XDocument
中?我想在xDoc.Root.Element("ReportSection").AddFirst(XElement)
之后得到以下输出:
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>
推荐答案
我不确定为什么会这样,但是从body元素中删除xmlns
属性似乎可行:
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);
这篇关于将XElement合并到XDocument中并解析名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!