Linq to XML没有得到结果 [英] Linq to XML not getting a result

查看:60
本文介绍了Linq to XML没有得到结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用linq到xml创建结构列表.

I am creating a List of structs using linq to xml.

linq路径找不到概念元素.我已经尝试过各种方法,在放弃使用xpath之前,我希望有人可以向我展示linq方式.谢谢

The linq path does not find the concept elements. I have tried various formulations of this and before I give up and use xpath I am hoping someone can show me the linq way. thanks

这是xml

<response xmlns="http://www.domain.com/api">
  <about>
    <requestId>E9B73CA1F16A670C966BE2BABD3B2B22</requestId>
    <docId>09E167D994E00B0F511781C40B85AEC3</docId>
    <systemType>concept</systemType>
    <configId>odp_2007_l1_1.7k</configId>
    <contentType>text/plain</contentType>
    <contentDigest>09E167D994E00B0F511781C40B85AEC3</contentDigest>
    <requestDate>2011-10-18T09:51:28+00:00</requestDate>
    <systemVersion>2.1</systemVersion>
  </about>
  <conceptExtractor>
    <conceptExtractorResponse>
      <concepts>
        <concept weight="0.010466908" label="hell"/>
      </concepts>
    </conceptExtractorResponse>
  </conceptExtractor>
</response>

这是我所拥有的

public struct conceptweight
{
    public string concept { get; set; }
    public string weight { get; set; }
}

List<conceptweight> list = (from c
  in d.Descendants("response")
      .Descendants("conceptExtractor")
      .Descendants("conceptExtractorResponse")
      .Descendants("concepts")
  select new conceptweight()
         {
           concept = c.Attribute("label").Value,
           weight = c.Attribute("weight").Value
         }).ToList();

推荐答案

您已经忘记了名称空间,该名称空间是根元素中默认使用的名称空间.试试这个:

You've forgotten the namespace, which is defaulted in the root element. Try this:

// Note: names changed to follow conventions, and now a class
// rather than a struct. Mutable structs are evil.
public class ConceptWeight
{
    public string Concept { get; set; }
    // Type changed to reflect the natural data type
    public double Weight { get; set; }
}

XNamespace ns = "http://www.domain.com/api";

// No need to traverse the path all the way, unless there are other "concepts"
// elements you want to ignore. Note the use of ns here.
var list = d.Descendants(ns + "concepts")
            .Select(c => new ConceptWeight
                    {
                        Concept = (string) c.Attribute("label"),
                        Weight = (double) c.Attribute("weight"),
                    })
            .ToList();

我这里没有使用查询表达式,因为它没有添加任何值-您只在执行from x in y select z,这更简单地通过Select扩展方法表示.

I haven't used a query expression here as it wasn't adding any value - you were only doing from x in y select z, which is more simply expressed via the Select extension method.

这篇关于Linq to XML没有得到结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆