Best way to query XDocument with LINQ?

前端 未结 2 1195
情歌与酒
情歌与酒 2020-12-16 13:05

I have an XML document that contains a series of item nodes that look like this:


    
        
                


        
相关标签:
2条回答
  • 2020-12-16 13:40

    use XPATH - it is very fast ( except xmlreader - but a lot of if's)

       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 );
         }
    
        }
    
    0 讨论(0)
  • 2020-12-16 13:41

    I would use the built-in query methods in LINQ to XML instead of XPath. Your query looks fine to me, except that:

    • If there are multiple items, you'd need to find the descendants of that instead; or just use Element if you're looking for direct descendants of the item
    • You may want to pull all the values at once and convert them into a dictionary
    • If you're using different data types for the contents, you might want to cast the element instead of using .Value
    • You may want to create a method to return the matching XElement for a given type, instead of having several queries.

    Personally I don't think I'd even use a query expression for this. For example:

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

    Then:

    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")
                 };
    

    I suspect you'll find that's neater than any alternative using XPath, assuming I've understood what you're trying to do.

    0 讨论(0)
提交回复
热议问题