繁体   English   中英

使用LINQ查询XDocument的最佳方法?

[英]Best way to query XDocument with LINQ?

我有一个XML文档,其中包含一系列项目节点,如下所示:

<data>
    <item>
        <label>XYZ</label>
        <description>lorem ipsum</description>
        <parameter type="id">123</parameter>
        <parameter type="name">Adam Savage</parameter>
        <parameter type="zip">90210</parameter>
    </item> 
</data>

我想将它LINQ成一个匿名类型,如下所示:

var mydata =
    (from root in document.Root.Elements("item")
    select new {
       label = (string)root.Element("label"),
       description = (string)root.Element("description"),
       id = ...,
       name = ...,
       zip = ...
     });

根据“类型”属性的值拉取每个参数类型的最佳方法是什么? 由于有许多参数元素,因此您最终会使用root.Elements("parameter")作为集合。 我能想到的最好的方法是通过下面的方法,但我觉得必须有更好的方法吗?

(from c in root.Descendants("parameter") where (string)c.Attribute("type") == "id"
select c.Value).SingleOrDefault()

我会使用LINQ to XML中的内置查询方法而不是XPath。 您的查询对我来说很好,除了:

  • 如果有多个项目,你需要找到它的后代; 或者如果您正在寻找该项目的直接后代,请使用Element
  • 您可能希望一次拉出所有值并将它们转换为字典
  • 如果您对内容使用不同的数据类型,则可能需要转换元素而不是使用.Value
  • 您可能希望创建一个方法来返回给定类型的匹配XElement ,而不是具有多个查询。

我个人认为我甚至不会使用查询表达式。 例如:

static XElement FindParameter(XElement element, string type)
{
    return element.Elements("parameter")
                  .SingleOrDefault(p => (string) p.Attribute("type") == type);
}

然后:

var mydata = from item in document.Root.Elements("item")
             select new {
                 Label = (string) item.Element("label"),
                 Description = (string) item.Element("description"),
                 Id = (int) FindParameter(item, "id"),
                 Name = (string) FindParameter(item, "name"),
                 Zip = (string) FindParameter(item, "zip")
             };

我怀疑你会发现它比使用XPath的任何替代方案更整洁,假设我已经理解你正在尝试做什么。

使用XPATH - 它非常快(除了xmlreader - 但很多 if)

   using (var stream = new StringReader(xml))
   {
    XDocument xmlFile = XDocument.Load(stream);

    var query = (IEnumerable)xmlFile.XPathEvaluate("/data/item/parameter[@type='id']");

     foreach (var x in query.Cast<XElement>())
     {
         Console.WriteLine(  x.Value );
     }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM