2010-06-29 104 views
0

我有以下几点:过滤你的LINQ to XML查询

XDocument xdoc = XDocument.Load("C:\\myfile.xml"); 

List<Tag> list = new List<Tag>(); 

foreach (var tag in xdoc.Descendants("META")) 

{ 

string name = tag.Attribute("name").Value; 

string value = tag.Element("value").Value; 

list.Add(new Tag { Name = name, Value = value, Score = score, Key = key }); 

} 

,但我只需要获得条元件下的META元素。

我可以以某种方式将它添加到linq查询吗?

的XML看起来与此类似:

<DOCUMENT> 
    <META name="aaa"/> 
    <ARTICLE> 
    <META name="bbb" value="708" score="0.58" key="6008"/> 
    </ARTICLE> 
</DOCUMENT> 

感谢您的任何建议

最后,我需要做类似如下:

XDocument xdoc = XDocument.Load(tr); 
var meta = from el in xdoc.Descendants("ARTICLE").Elements("META") 
where (string) el.Attribute("name") == "RAW" 
select el; 

List<Tag> list = new List<Tag>(); 
foreach (var tag in meta) 
{ 
string name = tag.Attribute("name").Value; 
string value = tag.Attribute("value").Value; 
string score = tag.Attribute("score").Value; 
string key = tag.Attribute("key").Value; 

list.Add(new Tag { Name = name, Value = value, Score = score, Key = key }); 
}  

这样做的原因是我需要匹配名称等于RAW的属性。

如果有更好的方法来做到这一点,请纠正我!

回答

2

任何地方发现了他们在文件中,使用xdoc.Descendants("ARTICLE")找到所有ARTICLE元素,然后Elements("META")从那里找到所有直接META子元素。

此外,您可以进行投影,并在相同的查询转换到一个列表:

var list = xdoc.Descendants("ARTICLE") 
       .Elements("META") 
       .Select(x => new Tag { Name = (string) x.Attribute("name"), 
             Value = (string) x.Attribute("value"), 
             Key = key }) 
       .ToList();