I am interested to know how to read the following XML in the most elegant / cleanest way possible. (snippet)
<Config>
<MyTag />
<MyTag />
</Config>
<Config>
<MyTag />
<MyTag />
<MyTag />
</Config>
I want to read in the MyTag
nodes only. My first thought was LINQ but didn't know if it was cleaner using XPath.
It is a lot cleaner to use XPath:
foreach(XElement myTag in (IEnumerable)XDocument.Load(xmlFile)
.XPathEvaluate("/xml/Config/MyTag"))
{
}
The LINQ equivalent would be:
foreach(var myTag in XDocument.Load(xmlFile).Root.Elements("Config")
.SelectMany(x => x.Elements("MyTag")))
{
}
My answer assumes that there is a xml
tag around the Config
tags, because otherwise the xml file wouldn't be valid.
You describe which tags you're after in the question so it might be a matter of style. But is it possible the query will be different in the future? That is, might the query be formed at run-time? I ask becuase XPath might be the way to go becuase it's a query string. LINQ can be very flexible but you do need to know more about the structure of the XML and the query to build an expression.
VB.Net has (imo) the most elegant way :
Dim xml = <XML>
<Config>
<MyTag>1</MyTag>
<MyTag>2</MyTag>
</Config>
<Config>
<MyTag>3</MyTag>
<MyTag>4</MyTag>
<MyTag>5</MyTag>
<MyTag>6</MyTag>
</Config>
</XML>
xml.Descendants("MyTag").ToList.ForEach(Sub(x)
Console.WriteLine("MyTag = {0}", x.Value)
End Sub)
Console.ReadLine()
精彩评论