开发者

A question of style: LINQ or XPath to read in XML nodes [closed]

开发者 https://www.devze.com 2023-03-16 23:30 出处:网络
开发者_运维知识库 As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely
开发者_运维知识库 As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消