Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从xml中的单个元素中提取值_C#_Xml_Xml Parsing - Fatal编程技术网

C# 从xml中的单个元素中提取值

C# 从xml中的单个元素中提取值,c#,xml,xml-parsing,C#,Xml,Xml Parsing,我正在使用来自wcf服务的soap响应,并希望从各个元素中提取值。到目前为止,我能够使用以下方法从soap信封中获取值列表: XDocument xDoc = XDocument.Parse(ServiceResult); List<XElement> ResultsView = xDoc.Descendants() .Where(x => x.Name.LocalName == "ResultsView")

我正在使用来自wcf服务的soap响应,并希望从各个元素中提取值。到目前为止,我能够使用以下方法从soap信封中获取值列表:

XDocument xDoc = XDocument.Parse(ServiceResult);

List<XElement> ResultsView = xDoc.Descendants()
                                 .Where(x => x.Name.LocalName == "ResultsView")
                                 .ToList();

问题是您要求的元素没有名称空间。如果使用正确的名称空间,则不需要检查本地名称或类似的内容:

XNamespace ns = "http://schemas.datacontract.org/2004/07/LoacalWcf";
XDocument doc = XDocument.Parse(ServiceResult);

XElement resultsView = doc.Descendants(ns + "ResultsView").Single();
XElement duration = resultsView.Element(ns + "Duration");
注意使用
+
操作符从
XNamespace
字符串创建
XName


(看起来你很可能想将
duration
转换为
int
而不是
string
,以语义有用的形式获取值。)

听起来你好像尝试了什么,但没有成功-请你展示一下你尝试过的内容好吗?了解别名
a
的名称空间URI也会很有帮助。(请求具有该名称的子体比只使用
LocalName
part,IMO更好)返回的完整soap信封是:您可以获得结果视图的独立元素,如=>
List ResultsView=xDoc.element(“ResultsView”).Elements().ToList()谢谢你的两个回复,我已经能够得到我想要的。
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetLocalDataResponse xmlns="http://tempuri.org/">
<GetLocalDataResult xmlns:a="http://schemas.datacontract.org/2004/07/LocalWcf"
 xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:ResultsView>
<a:Duration>4032</a:Duration>
<a:Metres>41124</a:Metres>
<a:Status>Ok</a:Status>
</a:ResultsView>
</GetLocalDataResult></GetLocalDataResponse></s:Body></s:Envelope>
 var results = ResultsView.Select(x => new
            {
                ResultsView = (string)x.Element("Duration"),
                duration = x.Element("Duration")
            });
XNamespace ns = "http://schemas.datacontract.org/2004/07/LoacalWcf";
XDocument doc = XDocument.Parse(ServiceResult);

XElement resultsView = doc.Descendants(ns + "ResultsView").Single();
XElement duration = resultsView.Element(ns + "Duration");