0

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?

DaveDev
  • 41,155
  • 72
  • 223
  • 385

5 Answers5

1

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();
Philipp Schmid
  • 5,778
  • 5
  • 44
  • 66
1

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.

Community
  • 1
  • 1
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
0

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;
L.B
  • 114,136
  • 19
  • 178
  • 224
0

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

that should put the value 0 into stat.

Stuart
  • 1,123
  • 8
  • 24
0

Your xml code use Namespace.

XNamespace  ns = "http://www.xyz.com/ns/2006/05/01/webservices/abc/def";
var stat = _xml.Descendants(ns + "Status");
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70