我有这个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的应用程序。
发布于 2012-12-12 18:15:57
是的,您需要递归地为所有新元素提供命名空间:
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> https://stackoverflow.com/questions/13837220
复制相似问题