简体   繁体   中英

How to parse xml with Linq?

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?

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

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM