Stephen Carey
Stephen Carey

Reputation: 11

attempting to get list items from xml linq query

I am trying to iterate over a list of elements in an xml document and return each elements value in the form of a list. However it gives back all the values in a single list item, concatenating them together. Is there any way i can separate each elements value into its own list item??

Thanks in advance, At the moment it returns "Item1Item2Item3" - same list item

  public List<string> ReturnRow(string RowToReturn, string parentelement)
            {
            List<XElement> ElementList = new List<XElement>();
            List<string> ItemstoReturn = new List<string>();
            try
            {
                //loop through whole doc and get blocks that match the Row (should only be 1)
                ItemstoReturn = (from element in XmlDoc.Root.Elements(parentelement)
                                 where element.Attribute(ParentAttribName).Value == RowToReturn
                                 select element.Value).ToList();

                //loop through inner elements to retrieve values 
                foreach (XElement eachelement in ElementList)
                {
                    ItemstoReturn.Add(eachelement.Value);
                }
                //return values to list
                return ItemstoReturn;
            }
            catch(Exception ex)
            {
                ex.ToString();
                return null;
            }
        }

Upvotes: 0

Views: 333

Answers (1)

Krishna Varma
Krishna Varma

Reputation: 4260

Input XML

<recipes>
  <recipe name="vidmar"/>
  <recipe name="oven">
      <ESN>25058301</ESN>
      <ESN>25058302</ESN>
  </recipe>
</recipes>

Using XElement, I am able to read ESN values using LINQ

using System.Xml.Linq; //namespace
...

string xml = File.ReadAllText(xmlFilePath);

XElement doc = XElement.Parse(xml);
var result = doc.Elements("recipe")
                .Where(c => c.Attribute("name").Value == "oven");

foreach(var element in result.Descendants("ESN"))
{
    Console.WriteLine(element.Value.ToString());
}

Upvotes: 1

Related Questions