Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.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 - Fatal编程技术网

C# 从xml字符串检索数据

C# 从xml字符串检索数据,c#,xml,C#,Xml,我正在使用c#从guardian web服务检索数据。我得到的答案是xml字符串,类似这样 < results > < content > < fields > < field name="headlines"> This is headline < /field> < field name="text"> This is text < /field> <field name="url"> Th

我正在使用c#从guardian web服务检索数据。我得到的答案是xml字符串,类似这样

< results >

< content >

< fields >

< field name="headlines"> This is headline < /field>
< field name="text"> This is text < /field>
<field name="url"> This is url < /field>
< fields>
< /content>
< content>
.........
< /content>
....
< results>
那么:

var fieldName = "text";
var text =
    xmlStories
    .Descendants("field")
    .Where(e => e.Attribute("name").Value.Equals(fieldName));
这将有助于:

var head = xmlStories.Descendants("field")
                     .Where(field =>(string)field.Attribute("name") == "text")
                     .Select(field => new
                      {
                        Text = (string)field,
                      })
                     .ToList();
注意
.Where()
条件中的强制转换字符串,这将涵盖属性
名称
完全不存在的情况。 如果您只想要一个包含该单字符串属性内容的列表,则也不需要匿名类,更短的是:

var head = xmlStories.Descendants("field")
                     .Where(field =>(string)field.Attribute("name") == "text")
                     .Select(field => (string)field)
                     .ToList();
这将是一个字符串列表

var head = xmlStories.Descendants("field")
                     .Where(field =>(string)field.Attribute("name") == "text")
                     .Select(field => (string)field)
                     .ToList();