开发者

How can I get the Status element from the following XML?

开发者 https://www.devze.com 2023-04-13 06:12 出处:网络
I\'m getting the following block of xml back from a web service: <?xml version=\"1.0\" encoding=\"utf-16\"?>

I'm getting the following block of xml back from a web service:

<?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>

I'm trying to capture the Status element in an object as follows, but it's not working.

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

What's the best way for me to get this element?


If you want to use System.Xml.Linq, you can use this expression:

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


You are not able to get the required results with your existing code because of the xmlns attribute in Item

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

This question addresses the problem you are actually facing. If you don't know the namespace then you should take a look at this question.


I don't know the best way, but you can read it like this

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


use xpath, something like var stat = _xml.SelectSingleNode(@"ArrayOfItemResponse/ItemResponse/ItemStatus/StatusCode").Value;

that should put the value 0 into stat.


Your xml code use Namespace.

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

精彩评论

暂无评论...
验证码 换一张
取 消