如何访问更深层次的xdocument节点?

时间:2013-01-15 20:17:29

标签: c# xml linq-to-xml

我有以下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>

我可以访问&#34; Invoice_Number&#34;和&#34;状态&#34;具有以下代码的节点,但我不确定如何获取&#34; ErrorMessage&#34;节点。这就是我所拥有的:

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;
}

但是如何获得ErrorMessage?我试过了

string error = invoice.Element("Detail_Errors").Element("Detail_Error").Element("ErrorMessage").Value;

但是这给了我一个&#34;对象引用没有设置为对象的实例&#34;错误。

怎么办呢?谢谢!!

1 个答案:

答案 0 :(得分:1)

您提供的代码适用于您提供的XML。我怀疑你确实收到了一张没有 任何错误的发票 - 这就是错误的。

你应该循环错误:

foreach (var error in invoice.Elements("Detail_Errors").Elements("Detail_Error"))
{
    var id = error.Element("ErrorID").Value;
    var message = error.Element("ErrorMessage").Value;
    // Do whatever you want with the ID and message
}

请注意此处使用Elements("Detail_Errors") - 如果总是只有一个Detail_Errors元素(可能没有子元素),您可以使用Element("Detail_Errors")但是即使有没有 Detail_Errors元素,我给出的代码也会有效。

相关问题