c# - 添加元素时 xmlns 属性创建为空

标签 c# linq-to-xml

我有这个 xml 文件:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<S2SDDIdf:MPEDDIdfBlkDirDeb xmlns:S2SDDIdf="urn:S2SDDIdf:xsd:$MPEDDIdfBlkDirDeb"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:S2SDDIdf:xsd:$MPEDDIdfBlkDirDeb MPEDDIdfBlkDirDeb.xsd">

  <S2SDDIdf:SndgInst>CHASDEFX</S2SDDIdf:SndgInst>
  <S2SDDIdf:RcvgInst>BOFIIE2D</S2SDDIdf:RcvgInst>
  <S2SDDIdf:pacs.003.001.01 xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.003.001.01">


  </S2SDDIdf:pacs.003.001.01>
</S2SDDIdf:MPEDDIdfBlkDirDeb>

我在元素 S2SDDIdf:pacs.003.001.01 下添加此元素:

<DrctDbtTxInf>
    <PmtId>
        <EndToEndId>DDIE2EA00033</EndToEndId>
        <TxId>DDITXA00033</TxId>
    </PmtId>
</DrctDbtTxInf>

代码如下:

// Read pacs.003.001.01 element
XElement bulk = XElement.Parse(File.ReadAllText("_Bulk.txt"));

// Read DrctDbtTxInf element
XElement tx = XElement.Parse(File.ReadAllText("_Tx.txt"));

// Add DrctDbtTxInf element to pacs.003.001.01 element
bulk.Element("{urn:S2SDDIdf:xsd:$MPEDDIdfBlkDirDeb}pacs.003.001.01").Add(tx);

问题是元素 DrctDbtTxInf 得到一个空的 xmlns 属性:

<DrctDbtTxInf xmlns="">

我该如何摆脱它?我尝试在 DrctDbtTxInf 元素中提供与 pacs.003.001.01 中相同的 namespace ,但它只是停留在那里,这会破坏读取 xml 的应用程序。

最佳答案

是的,您需要为所有新元素递归地提供命名空间:

public static class Extensions
{
    public static XElement SetNamespaceRecursivly(this XElement root,
                                                  XNamespace ns)
    {
        foreach (XElement e in root.DescendantsAndSelf())
        {
            if (e.Name.Namespace == "")
                e.Name = ns + e.Name.LocalName;
        }

        return root;    
    }
}


XNamespace ns = "urn:iso:std:iso:20022:tech:xsd:pacs.003.001.01";

// Add DrctDbtTxInf element to pacs.003.001.01 element
bulk.Element("{urn:S2SDDIdf:xsd:$MPEDDIdfBlkDirDeb}pacs.003.001.01")
    .Add(tx.SetNamespaceRecursivly(ns));

这将产生以下 XML:

<S2SDDIdf:MPEDDIdfBlkDirDeb xmlns:S2SDDIdf="urn:S2SDDIdf:xsd:$MPEDDIdfBlkDirDeb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:S2SDDIdf:xsd:$MPEDDIdfBlkDirDeb MPEDDIdfBlkDirDeb.xsd">
  <S2SDDIdf:SndgInst>CHASDEFX</S2SDDIdf:SndgInst>
  <S2SDDIdf:RcvgInst>BOFIIE2D</S2SDDIdf:RcvgInst>
  <S2SDDIdf:pacs.003.001.01 xmlns="urn:iso:std:iso:20022:tech:xsd:pacs.003.001.01">
    <DrctDbtTxInf>
      <PmtId>
        <EndToEndId>DDIE2EA00033</EndToEndId>
        <TxId>DDITXA00033</TxId>
      </PmtId>
    </DrctDbtTxInf>
  </S2SDDIdf:pacs.003.001.01>
</S2SDDIdf:MPEDDIdfBlkDirDeb> 

关于c# - 添加元素时 xmlns 属性创建为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13837220/

相关文章:

c# - 通过接口(interface)使用静态类?

c# - 在 C# 中,如何在 Console.WriteLine() 中使用占位符?

c# - 最好的 OAuth2 C# 库是什么?

c# - 如何获取 xml 元素的特定子元素?

c# - linq 问题 : querying nested collections

c# - 如何将 OrderBy 添加到此 LINQ 语句?

c# - 如何使用正则表达式从字符串中获取数字?

C# 可空相等操作,为什么 null <= null 解析为 false?

c# - Linq to XML 嵌套查询

c# - Linq 选择字母之间的范围,例如。 a-e