如何从下面的XML中获得Status元素?
本文关键字:Status 元素 XML | 更新日期: 2023-09-27 18:11:29
我从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");
获取这个元素的最好方法是什么?
如果您想使用System.Xml。Linq,你可以使用这个表达式:
var stat = (from n in _xml.Descendants() where n.Name.LocalName == "Status" select n).ToList();
由于Item
中的xmlns属性,您无法使用现有代码获得所需的结果 <Item xmlns="http://www.xyz.com/ns/2006/05/01/webservices/abc/def">
这个问题解决了你实际面临的问题。如果您不知道名称空间,那么您应该看看这个问题。
我不知道最好的方法,但你可以这样读
XmlDocument xdoc = new XmlDocument();
xdoc.Load(stream);
var statMsg = xdoc.GetElementsByTagName("StatusMsg")[0].InnerText;
var statCode = xdoc.GetElementsByTagName("StatusCode")[0].InnerText;
使用xpath,类似于var stat = _xml.SelectSingleNode(@"ArrayOfItemResponse/ItemResponse/ItemStatus/StatusCode").Value;
将值0放入stat.
您的xml代码使用命名空间
XNamespace ns = "http://www.xyz.com/ns/2006/05/01/webservices/abc/def";
var stat = _xml.Descendants(ns + "Status");