1

Hi I have xml string like you can see below

 <?xml version="1.0" encoding="ISO-8859-1" ?> 
- <Result>
    - <AllItems>
        - <Item attribute="123">
              <SubItem subAttribute="1" /> 
              <SubItem2 subAttribute2="2" /> 
          </Item>
        - <Item attribute="321">
              <SubItem subAttribute="3" /> 
              <SubItem2 subAttribute2="4" /> 
          </Item>
      </AllItems>
  </Result>

I would like to get each item in allitems element get attribute values and add them to Enumerable class

Enumerable<Item> allitems = new Enumerable<Item>();

public class Item()
{
     public string attribute{get;set;}
     public string subattribute{get;set;}
     public string subattribute2{get;set;}
}

How it can be done with using LINQ?

2
  • there is no such class as Enumerable<T>. Use List<T> instead.
    – jeroenh
    Apr 27, 2011 at 15:46
  • 1
    possible duplicate of LINQ to read XML (C#)
    – jeroenh
    Apr 27, 2011 at 15:49

3 Answers 3

3

Your example would look like this in Linq to XML:

XDocument doc = XDocument.Load("test.xml");
var allItems = doc.Descendants("Item").Select(x => new Item() 
{
    attribute = x.Attribute("attribute").Value,
    subattribute = x.Element("SubItem").Attribute("subAttribute").Value,
    subattribute2 = x.Element("SubItem2").Attribute("subAttribute2").Value
});

foreach (var item in allItems)
{
    Console.WriteLine(string.Format("{0}: {1} / {2} ", item.attribute, 
                                                       item.subattribute, 
                                                       item.subattribute2));
}
0
2

Here's something that will directly translate into your class:

var allItems = from item in XDocument.Load("myxmlfile.xml").Descendants("Item")
    select new Item()
    {
        attribute = (string)item.Attribute("attribute"),
        subattribute = (string)item.Element("SubItem1").Attribute("subAttribute"),
        subattribute2 = (string)item.Element("SubItem2").Attribute("subAttribute")
    };

foreach(Item item in allItems)
{
    // your logic here
}
1

You have LINQ to XML which you can use to query XML with LINQ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.