我收到一个包含 XML 响应的状态对象。
此响应可以是“成功”消息、“错误”消息或 null(尚未处理,因此没有消息)。
我想不出一种优雅的方式来解析这个 XML。
我能想到的唯一两个选项是尝试解析每个错误消息上的 XML 字符串,或者执行 String.Contains("Success") 或 String.Contains("Error")。
在这两种方法中,TryParse 似乎是最好的……但看起来仍然很丑。
我想知道是否有更好的方法来处理这个问题。
接收对象可能如下所示:
public class ReturnedObject{
    public string MessageId
    public string MessageDescription
    public string XML
}
XML 可以为 null 或以下示例之一:
<Success>
    <paymentReference>123</paymentReference>
    <targetBankAccount>01-0002-3948</targetBankAccount>
</Success>
或者
<Error>
    <errorMessage>Your bank account was invalid</errorMessage>
    <errorBelongsToField>BankNumber</errorBelongsToField>
</Error>
我当前的解析器看起来像:
        if (documentStatusResponse.Xml == null)
        {
            return disassociatedDocumentStatusResponse;
        }
        var root = XDocument.Parse(documentStatusResponse.Xml).Root;
        if (root != null)
        {
            if (root.Name == "Error")
            {
                disassociatedDocumentStatusResponse.Errors = _xmlExtractor.RetrieveStatusErrors(documentStatusResponse.Xml);
            }
            else if (root.Name == "Success")
            {
                disassociatedDocumentStatusResponse.Reconciliation =
                    _xmlExtractor.RetrieveStatusReconciliation(documentStatusResponse.Xml);
            }
        }