更改XML文档时,用户代码未处理NullReferenceException

时间:2014-08-04 07:46:44

标签: c# xml nullreferenceexception

我收到错误:NullReferenceException未被用户代码处理,对象引用未设置为对象的实例。虽然我想更改xml文件的元素。这是生成错误的代码:

doc2.SelectSingleNode("/Document/CstmrCdtTrfInitn/GrpHdr/MsgId", nsmgr).InnerText = bank.Afkorting + "-0001";

这是上一段代码:

XmlDocument doc2 = new XmlDocument();
doc2.Load(@"C:\Users\Kevin\Desktop\xsd\betalingen_sepa.xml");

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc2.NameTable);
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

DagboekFinancieel bank = os.FindObject<DagboekFinancieel>(CriteriaOperator.Parse("[Omschrijving] = ?", opdracht.Bank));
doc2.SelectSingleNode("/Document/CstmrCdtTrfInitn/GrpHdr/MsgId", nsmgr).InnerText = bank.Afkorting + "-0001";

string naamFile = bank.Afkorting + "-0001";
doc2.Save(@"C:\" + naamFile + ".xml");

这是我收到的原始XML文件:

<?xml version="1.0" encoding="UTF-8"?>

<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">


<CstmrCdtTrfInitn>
<GrpHdr>
<MsgId>@ref_xml@</MsgId>
<CreDtTm>@datum_tijd_xml@</CreDtTm>
<NbOfTxs>@aantal_transacties@</NbOfTxs>
<InitgPty>
<Nm>@afzender_naam@</Nm>
<Id>
<OrgId>
<Othr>
<Id>@afzender_btw_nr@</Id>
<Issr>KBO-BCE</Issr>
</Othr>
</OrgId>
</Id>
</InitgPty>
</GrpHdr>
<PmtInf>
<PmtInfId>@ref_payment_block@</PmtInfId>
<PmtMtd>TRF</PmtMtd>
<BtchBookg>true</BtchBookg>
<PmtTpInf>
<SvcLvl>
<Cd>SEPA</Cd>
</SvcLvl>
</PmtTpInf>
<ReqdExctnDt>@datum_uitvoering@</ReqdExctnDt>
<Dbtr>
<Nm>@afzender_naam@</Nm>
</Dbtr>
<DbtrAcct>
<Id>
<IBAN>@afzender_iban@</IBAN>
</Id>
</DbtrAcct>
<DbtrAgt>
<FinInstnId>
<BIC>@afzender_bic@</BIC>
</FinInstnId>
</DbtrAgt>
<ChrgBr>@kosten@</ChrgBr>
<CdtTrfTxInf>
<PmtId>
<EndToEndId>@ref_end_to_end@</EndToEndId>
</PmtId>
<Amt>
<InstdAmt Ccy="@munt@">@bedrag@</InstdAmt>
</Amt>
<CdtrAgt>
<FinInstnId>
<BIC>@leveran_bic@</BIC>
</FinInstnId>
</CdtrAgt>
<Cdtr>
<Nm>@leveran_naam@</Nm>
<PstlAdr>
<Ctry>@leveran_land@</Ctry>
<AdrLine>@leveran_straat@</AdrLine>
<AdrLine>@leveran_wpl@</AdrLine>
</PstlAdr>
</Cdtr>
<CdtrAcct>
<Id>
<IBAN>@leveran_iban@</IBAN>
</Id>
</CdtrAcct>
<RmtInf>
<Ustrd>@leveran_ref@</Ustrd>
<Strd>
<CdtrRefInf>
<Tp>
<CdOrPrtry>
<Cd>@gestruct_mededeling_soort1@</Cd>
</CdOrPrtry>
<Issr>@gestruct_mededeling_soort2@</Issr>
</Tp>
<Ref>@gestruct_mededeling@</Ref>
</CdtrRefInf>
</Strd>
</RmtInf>
</CdtTrfTxInf>
</PmtInf>
</CstmrCdtTrfInitn>
</Document>

1 个答案:

答案 0 :(得分:1)

您的xml命名空间不正确。像

一样使用它
nsmgr.AddNamespace("ns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03");
doc2.SelectSingleNode("/ns:Document/ns:CstmrCdtTrfInitn/ns:GrpHdr/ns:MsgId", nsmgr).InnerText = "some text";