2011-10-18 161 views
1

我正在创建一个使用linq to xml的结构列表。Linq to XML没有得到结果

linq路径找不到概念元素。我已经尝试过不同的配方,在放弃和使用xpath之前,我希望有人能够向我展示linq的方式。感谢

这里是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(); 
+0

你是如何加载'd'的? –

回答

1

你忘了命名空间,这是在根元素拖欠。试试这个:

// 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扩展方法来表示。

+0

啊谢谢。现在可以正常工作,并且通过循环xmlnodes构建结构当然更加优雅。 – Jules

0
XNamespace n = "http://www.domain.com/api"; 
List<conceptweight> list = (from c in d.Elements(n + "response").Elements(n + "conceptExtractor").Elements(n + "conceptExtractorResponse").Elements(n + "concepts").Elements(n + "concept") 
          select new conceptweight 
          { 
           concept = c.Attribute("label").Value, 
           weight = c.Attribute("weight").Value 
          }).ToList(); 

您忘记了命名空间和最后一个元素(concept)。啊,如果你进行内联初始化,你不需要new conceptweight中的()括号。 Ah和Descendants将遍历元素的所有“级别”。如果您想“手动”遍历它,请使用Elements