I have the following:
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 });
}
but I need to only get the META elements under the element ARTICLE.
Can I add this to the linq query somehow?
The xml looks similar to this:
<DOCUMENT>
<META name="aaa"/>
<ARTICLE>
<META name="bbb" value="708" score="0.58" key="6008"/>
</ARTICLE>
</DOCUMENT>
Thanks for any suggestions
In the end I need to do something like the following:
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 });
}
The reason for this is that I needed to match the attribute where the name was equal to RAW.
Please correct me if there’s a better way to do this!
To find them anywhere in the document, use
xdoc.Descendants("ARTICLE")to find all theARTICLEelements, and thenElements("META")from there to find all the directMETAchildren elements.In addition, you can perform the projection and the conversion to a list in the same query: