Linq到XML没有得到结果
本文关键字:结果 XML Linq | 更新日期: 2023-09-27 18:11:48
我正在使用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();
您忘记了名称空间,它默认在根元素中。试试这个:
// 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
扩展方法来表达。
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
。