2011-10-14 27 views
0

我得到下面的XML块从Web服务回:如何从以下XML获取状态元素?

<?xml version="1.0" encoding="utf-16"?> 
<ArrayOfItemResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <ItemResponse> 
     <Item xmlns="http://www.xyz.com/ns/2006/05/01/webservices/abc/def"> 
      <RequestKey Name="ESM.PA" Service="" /> 
      <QoS> 
       <TimelinessInfo Timeliness="REALTIME" TimeInfo="0" /> 
       <RateInfo Rate="TIME_CONFLATED" TimeInfo="10" /> 
      </QoS> 
      <Status> 
       <StatusMsg>OK</StatusMsg> 
       <StatusCode>0</StatusCode> 
      </Status> 
      <Fields> 
       <Field DataType="Utf8String" Name="DSPLY_NAME"> 
        <Utf8String>D15 |ASDFDSAA ETF </Utf8String> 
       </Field> 
      </Fields> 
     </Item> 
    </ItemResponse> 
</ArrayOfItemResponse> 

我试图捕捉状态元素中的对象如下,但它不工作。

var _xml = XDocument.Parse(xmlFromService); 
var stat = _xml 
    .Descendants("ArrayOfItemResponse") 
    .Descendants("ItemResponse") 
    .Descendants("Item") 
    .Descendants("Status"); 

什么,我得到这个元素的最佳方式?

回答

1

如果你想使用System.Xml.Linq的,你可以用这个表达式:

var stat = (from n in _xml.Descendants() where n.Name.LocalName == "Status" select n).ToList(); 
0

我不知道最好的方式,但你可以这样

XmlDocument xdoc = new XmlDocument(); 
xdoc.Load(stream); 
var statMsg = xdoc.GetElementsByTagName("StatusMsg")[0].InnerText; 
var statCode = xdoc.GetElementsByTagName("StatusCode")[0].InnerText; 
0

使用XPath的读它,像 var stat = _xml.SelectSingleNode(@"ArrayOfItemResponse/ItemResponse/ItemStatus/StatusCode").Value;

应该把值0到统计。

1

你不能与你现有的代码,以获得所需要的结果,因为的XMLNS项

属性
<Item xmlns="http://www.xyz.com/ns/2006/05/01/webservices/abc/def"> 

This问题解决了您实际面临的问题。如果你不知道命名空间,那么你应该看看this的问题。

0

您的xml代码使用命名空间。

XNamespace ns = "http://www.xyz.com/ns/2006/05/01/webservices/abc/def"; 
var stat = _xml.Descendants(ns + "Status");