我有这个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的应用程序。
答案 0 :(得分: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>