简体   繁体   中英

xmlns attribute created empty when adding element

I have this xml file:

<?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>

I am adding this element under element S2SDDIdf:pacs.003.001.01:

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

Here is the code:

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

The problem is that element DrctDbtTxInf gets an empty xmlns attribute:

<DrctDbtTxInf xmlns="">

How do I get rid if it? I tried to supply the same namespace as in pacs.003.001.01 in the DrctDbtTxInf element but then it just stays there which break the app that reads the xml.

Yes, you need to supply the namespace recursivly for all new elements:

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

This will result in the following 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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