[英]Using Linq to XML for XPath Style Document Searching
假设我有一个如下所示的Web服务响应:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<PMWSGetReportResponse xmlns="http://localhost/PCMilerWS/">
<PMWSGetReportResult>
<ReportResponse>
<Version>25.02</Version>
<Report>
<RptType>m</RptType>
<TripID>011535</TripID>
<StopNum>1</StopNum>
<MilesReport>
<StpLineType>
<SRStop>
<Region>NA</Region>
<Address1 />
<City>Mill Valley</City>
<State>CA</State>
<Zip>94941</Zip>
<Juris>Marin</Juris>
<Lat>37894200</Lat>
<Long>-122493488</Long>
</SRStop>
<LMiles>0.0</LMiles>
<TMiles>0.0</TMiles>
<LCostMile>0.00</LCostMile>
<TCostMile>0.00</TCostMile>
<LHours>0:00</LHours>
<THours>0:00</THours>
<LTolls>0.00</LTolls>
<TTolls>0.00</TTolls>
<LEstghg>0.0</LEstghg>
<TEstghg>0.0</TEstghg>
</StpLineType>
<StpLineType>
<SRStop>
<Region>NA</Region>
<Address1 />
<City>San Francisco</City>
<State>CA</State>
<Zip>94109</Zip>
<Juris>San Francisco</Juris>
<Lat>37790599</Lat>
<Long>-122418809</Long>
<StopWarning>False</StopWarning>
</SRStop>
<LMiles>13.2</LMiles>
<TMiles>13.2</TMiles>
<LCostMile>34.33</LCostMile>
<TCostMile>34.33</TCostMile>
<LHours>0:17</LHours>
<THours>0:17</THours>
<LTolls>12.50</LTolls>
<TTolls>12.50</TTolls>
<LEstghg>48.7</LEstghg>
<TEstghg>48.7</TEstghg>
</StpLineType>
</MilesReport>
</Report>
</ReportResponse>
</PMWSGetReportResult>
</PMWSGetReportResponse>
</soap:Body>
</soap:Envelope>
我一直在尝试使用Linq to XML来检索所有StpLineType节点的列表。 我已经尝试过这样做:
XDocument xdoc = XDocument.Load(new StringReader(soapResponse));
var results = xdoc.Descendants("StpLineType");
但是什么也没有返回。 我可以看到该文档已加载到xdoc中,但似乎无法正确查询它。 FWIW,我也尝试过:
XDocument xdoc = XDocument.Load(new StringReader(soapResponse));
XNamespace ns = "soap";
var results = xdoc.Descendants(ns + "StpLineType");
以防万一命名空间引起了问题-运气不好。
我想念什么?
尝试
XDocument xdoc = XDocument.Load(new StringReader(soapResponse));
XNamespace ns = "http://localhost/PCMilerWS/";
var results = xdoc.Descendants(ns + "StpLineType");
您将忽略此文档中的两个 XML名称空间!
<body>
标记位于soap
名称空间中 <PMWSGetReportResponse>
元素上定义的“默认”名称空间(无前缀)中 如果考虑到这一点-一切都会开始正常!
XDocument xdoc = XDocument.Load(new StringReader(soapResponse));
XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns = "http://localhost/PCMilerWS/";
var results = xdoc.Root.Element(soap + "Body").Descendants(ns + "StpLineType");
但是,主要的问题确实是:为什么您要手动解析SOAP响应? .....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.