LINQ query to parse content from XML to class

前端 未结 3 1143
广开言路
广开言路 2021-01-28 13:35

I have an xml from which I am trying to extract some information through LINQ query.
The format of the xml file looks like the following:


           


        
相关标签:
3条回答
  • 2021-01-28 14:11
    var xDoc = XDocument.Load(....);
    var result = xDoc.Descendants("NextItem")
      .Union(xDoc.Descendants("PreviousItem"))
      .Select(n => new {ID = n.Attribute("id").Value, Name =n.Name, Value =n.Value });
    

    --EDIT--

    var result = XDocument.Load(....)
                .Descendants("Sequences")
                .Select(n=> n.Descendants("NextItem")
                     .Union(n.Descendants("PreviousItem"))
                     .Select(n2 => new { ID = n2.Attribute("id").Value, Name = n2.Name, Value = n2.Value })
                );
    
    0 讨论(0)
  • 2021-01-28 14:23

    I'm not sure I understood the question, but you can easily take element/attribute value inside LINQ to XML select statement:

    var EnumerableContent = from item in XElement.Load("file.xml").Elements("NextItem")
                  select new Extract() { name = item.Value, _id = (int)item.Attribute("id") }
    
    0 讨论(0)
  • 2021-01-28 14:25

    hi i think this is what you expect.

    List<XElement> lstXElements = new List<XElement>();
            lstXElements.AddRange(GetDescendants("NextItem"));
            lstXElements.AddRange(GetDescendants("PreviousItem"));
    
            List<Extract> lstExtract = new List<Extract>();
    
            foreach (XElement objElement in lstXElements)
            {
                Extract objExtract = new Extract();
                objExtract._id = Convert.ToInt32(objElement.Attribute("id").Value);
                objExtract.name = (objElement.Name).LocalName;
                lstExtract.Add(objExtract);
            }
    List<XElement> GetDescendants(string strDescentName)
        {
            return ((XDocument.Load(Server.MapPath("XMLFile1.xml"))
                .Descendants(strDescentName))
                ).ToList<XElement>();
        }
    
    0 讨论(0)
提交回复
热议问题