【问题标题】:Retrieving data from xml string从 xml 字符串中检索数据
【发布时间】:2011-03-14 03:53:48
【问题描述】:

我正在使用 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>

问题是所有具有数据的节点都具有相同的名称,即“字段”。当我使用此代码时,它会从第一个字段节点返回数据,但我想要来自名为 text 的字段的数据。

  var head = xmlStories.Root.Descendants("fields").Select(results => new
                  {
                      Text = results.Element("field").Value,


                  }).ToList();

                  foreach (var results in head)
                  {



                     text [h] = results.Text;


                      h = h + 1;
                  }

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    怎么样:

    var fieldName = "text";
    var text =
        xmlStories
        .Descendants("field")
        .Where(e => e.Attribute("name").Value.Equals(fieldName));
    

    【讨论】:

      【解决方案2】:

      这可行:

      var head = xmlStories.Descendants("field")
                           .Where(field =>(string)field.Attribute("name") == "text")
                           .Select(field => new
                            {
                              Text = (string)field,
                            })
                           .ToList();
      

      注意.Where() 条件中的转换为字符串,这将涵盖属性name 根本不存在的情况。 如果您只想要一个包含该字符串属性内容的列表,您也不需要匿名类,更短的是:

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

      这将是一个字符串列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-09
        • 2018-03-08
        • 2022-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多