命名空间搜索未找到元素

时间:2016-03-29 15:17:10

标签: ruby xpath nokogiri microsoft-dynamics savon

我尝试解析XML响应以处理销售订单,但XPath搜索不起作用。

这是XML响应的片段:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <SalesOrderServiceFindResponse xmlns="http://schemas.microsoft.com/dynamics/2008/01/services">
            <SalesOrder xmlns="http://schemas.microsoft.com/dynamics/2008/01/documents/SalesOrder">
                <DocPurpose>Original</DocPurpose>
                <SenderId>bell</SenderId>
                <SalesTable class="entity">
                    <_DocumentHash>33e9a9be2bcafdb1edde17c4e12d1166</_DocumentHash>
                    <ConsTarget_JP>No</ConsTarget_JP>
                    <CurrencyCode>USD</CurrencyCode>
                    <CustAccount>ANDE01</CustAccount>
                    <CustGroup>Distributo</CustGroup>
                    <CustomsExportOrder_IN>No</CustomsExportOrder_IN>
                    <CustomsShippingBill_IN>No</CustomsShippingBill_IN>
                    <DAXIntegrationId>{5A1B9C05-99DD-4E4E-91F1-2702117CEF98}</DAXIntegrationId>
                    <Deadline>2016-03-31</Deadline>
                    <DeliveryDate>2016-03-01</DeliveryDate>
                    ...
                </SalesTable>
                <SalesTable>
                    ...
                </SalesTable>
            </SalesOrder>
        </SalesOrderServiceFindResponse>
    </s:Body>
</s:Envelope>

我尝试通过多个<SalesTable>实体,因此我可以在外部系统中处理数据。

但是,以下情况不起作用:

response = client.call(:find, 
        message_tag: :SalesOrderServiceFindRequest,
        message: {
            :query_criteria => {
                :@xmlns => "http://schemas.microsoft.com/dynamics/2006/02/documents/QueryCriteria",
                :criteria_element => {
                    :data_source_name => "SalesTable", 
                    :field_name => "CustGroup", 
                    :operator => "Equal",
                    :value1 => "Distributo",
                }
            }
        }
    )

这是空的:

puts response.xpath("//SalesTable")

这也是空的:

puts response.xpath("//SalesOrder/SalesTable", "xmlns" => "http://schemas.microsoft.com/dynamics/2008/01/documents/SalesOrder") # empty

这就是:

puts response.xpath("//SalesOrder", "xmlns" => "http://schemas.microsoft.com/dynamics/2008/01/documents/SalesOrder")

我不明白,因为我可以验证是否存在SalesTable元素,因此应该找到它,但它无效。

1 个答案:

答案 0 :(得分:2)

您需要在查询中包含名称空间前缀。您使用xmlns的事实并未使其自动应用:

response.xpath("//xmlns:SalesOrder", "xmlns" => "http://schemas.microsoft.com/dynamics/2008/01/documents/SalesOrder")

事实上,使用不同的前缀可能是值得的,例如

response.xpath("//so:SalesOrder", "so" => "http://schemas.microsoft.com/dynamics/2008/01/documents/SalesOrder")