简体   繁体   English

使用相同的名称空间将XElement添加到XDocument

[英]Adding XElement to XDocument with same namespace

I have a XDocument with the following structure where I want to add a bunch of XElements. 我有一个具有以下结构的XDocument,我想在其中添加一堆XElement。

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
  <CstmrCdtTrfInitn>
    <GrpHdr>
     ...
    </GrpHdr>
    <!-- loaded nodes go here -->
  <CstmrCdtTrfInitn>
</Document>

The XElements have the following structure: XElement具有以下结构:

<PmtInf xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
...
</PmtInf>

The problem is that the namespace in child nodes is not supported at the recipients side and since it is the same as the XDocument's namespace - it is redundant. 问题在于,接收者端不支持子节点中的名称空间,因为它与XDocument的名称空间相同-这是多余的。 How do I avoid/remove that namespace on the child nodes? 如何避免/删除子节点上的名称空间?

The code that I use right now: 我现在使用的代码:

var childNodes = new XElement(NameSpace + "GrpHdr", ...);
XElement[] loadedNodes = ...;//Loads from a service using XElement.Load
var content = new XElement(NameSpace + "CstmrCdtTrfInitn", childNodes,loadedNodes));

When calling Save on XElement or XDocument , there is a flags enum SaveOptions that allow you to control to some extent how the document is written to XML. XElementXDocument上调用Save时,有一个标志枚举SaveOptions允许您在某种程度上控制如何将文档写入XML。

The easiest way to achieve what you want (without traversing the structure to remove the redundant attributes) is to use one of these flags: OmitDuplicateNamespaces . 实现所需内容(不遍历结构以删除冗余属性)的最简单方法是使用以下标志之一: OmitDuplicateNamespaces

Remove the duplicate namespace declarations while serializing. 序列化时删除重复的名称空间声明。

You can see in this fiddle that adding this flag changes my example output from this: 您可以在这个小提琴中看到,添加此标志会更改我的示例输出:

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
  <CstmrCdtTrfInitn>
    <GrpHdr />
    <PmtInf xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">...</PmtInf>
  </CstmrCdtTrfInitn>
</Document>

To this: 对此:

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
  <CstmrCdtTrfInitn>
    <GrpHdr />
    <PmtInf>...</PmtInf>
  </CstmrCdtTrfInitn>
</Document>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM