Reputation: 11
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?
Upvotes: 1
Views: 1246
Reputation: 520
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
}
Upvotes: 2
Reputation: 161002
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));
}
Upvotes: 3
Reputation: 63310
You have LINQ to XML which you can use to query XML with LINQ
Upvotes: 1