C# 从xml字符串检索数据
我正在使用c#从guardian web服务检索数据。我得到的答案是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
< 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();