【问题标题】:Select child element of SoapException.Detail.InnerXML [duplicate]选择 SoapException.Detail.InnerXML 的子元素 [重复]
【发布时间】:2016-12-15 17:48:12
【问题描述】:

我正在调用 UPS 网络服务来计算运费,如果地址无效,服务调用会返回 SoapException。

SoapException 有一个带有以下 XML 的 Detail.InnerXMl 属性:

<err:Errors xmlns:err=\"http://www.ups.com/XMLSchema/XOLTWS/Error/v1.1\">
    <err:ErrorDetail>
        <err:Severity>Hard</err:Severity>
        <err:PrimaryErrorCode>
            <err:Code>111286</err:Code>
            <err:Description>CAa is not a valid state for the specified shipment.</err:Description>
        </err:PrimaryErrorCode>
    </err:ErrorDetail>
</err:Errors>

我希望从&lt;Description&gt; 元素中提取文本。

为什么这不起作用:

try
{
}
catch (SoapException ex)
{
    XmlNode node = ex.Detail.SelectSingleNode("//Description");
    //node is null
}

【问题讨论】:

    标签: c# web-services xpath soap


    【解决方案1】:

    使用 LinqToXml 轻松解析 xml:

    var errors = XDocument.Parse(yourxmlstring)
                    .Descendants("errors")
                    .Select(e => new
                    {
                        code = (int)e.Element("code"),
                        desc = (string)e.Element("description")
                    })
                    .ToList();
    

    【讨论】:

    • 这将返回一个大小为 0 的列表,使用 ex.Detail.InnerXML 代替您的 yourxmlstring
    • yourxmlstring 应该包含您完整的 SoapException 响应消息。
    猜你喜欢
    • 2016-03-13
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多