1

私はこの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 と同じ名前空間を提供しようとしましたが、そこにとどまり、xml を読み取るアプリが壊れます。

4

1 に答える 1

4

はい、すべての新しい要素に対して名前空間を再帰的に提供する必要があります。

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> 
于 2012-12-12T10:15:56.857 に答える