我有以下 XML 文件:
<Invoice_Ack>
<Invoices>
<Invoice>
<Invoice_Number>123456</Invoice_Number>
<Status>Rejected</Status>
<Detail_Errors>
<Detail_Error>
<ErrorID>0001</ErrorID>
<ErrorMessage>This is the error message</ErrorMessage>
</Detail_Error>
<Detail_Error>
<ErrorID>0502</ErrorID>
<ErrorMessage>This is another error message</ErrorMessage>
</Detail_Error>
</Detail_Errors>
</Invoice>
</Invoices>
</Invoice_Ack>
我可以使用以下代码访问“Invoice_Number”和“Status”节点,但我不确定如何获取“ErrorMessage”节点。这是我所拥有的:
XDocument doc = XDocument.Load(file);
foreach(var invoice in doc.Descendants("Invoice"))
{
string status = invoice.Element("Status").Value;
string invoicenum = invoice.Element("Invoice_Number").Value;
}
但是我如何获得错误消息?我试过
string error = invoice.Element("Detail_Errors").Element("Detail_Error").Element("ErrorMessage").Value;
但这给了我“对象引用未设置为对象的实例”错误。
这还能怎么做?谢谢!!