我有这个 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/