鉴于以下 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>
的 child .问题是如果通过 XElement.Parse(body.xml)
添加它,它保留了 namespace ,即使我认为应该删除 namespace (没有必要复制自身 - 已经在父级上声明)。如果我不指定命名空间,它会改为放置一个空的命名空间,因此它变为 <Body xmlns="">
.
有没有办法正确合并XElement
进入XDocument
?我想在 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
属性似乎可行:
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);
关于c# - 将 XElement 合并到 XDocument 中并解析 namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613917/