开发者

Search XML using LINQ

The below is my XML file. Based on the <type>, I need to get all the node values of <customers></customers>.

<?xml version='1.0' encoding='utf-8' ?>
<All>
    <Customers>
        <Customer>
            <Name> Brisbane </Name>
            <age> 18 </age>
            <id> 1234 </id>
            <type> owner </type>
        </Customer>

        <details>
            <address>  123,Brisbane </address>
            <location> Indonesia </location>
        </details>
        <contact>
            <phone> 123456789 </phone>
            <fax>   12548976 </fax>
        </contact>
    </Customers>

    <Customers>
        <Customer>
            <Name> Manila</Name>
            <age> 16 </age>
            <id> 1200 </id>
            <type> seller</type>
        </Customer>

        <details>
            <address>  Rich Street </address>
            <location> Fabia </location>
        </details>

       <contact>
           <phone> 987456321</phone>
           <fax>   23654897 </fax>
       </contact>
    </Customers>
</All>

For example, in the above example there are two types:

  1. owner
  2. seller.

S开发者_Go百科o if I choose "owner" I need to get the details as follows

Brisbane
18
1234
123,Brisbane
Indonesia
123456789
12548976

So if I choose "seller" I need to get the details as follows.

Manila
16
1200
Rich Street
Fabia
987456321
23654897

So how do I do this? What would some sample code for this?


OK say the XML is called "doc".

        var results_sellers = (from item in doc.Descendants("Customer")
                               where (string)item.Element("type") == "seller"
                               select new { 
                                   Name = item.Element("Name").Value,
                                   Age = item.Element("Age").Value,
                                   Id = item.Element("Id").Value,
                                   Type = item.Element("type").Value
                               });

        //Then you can do the following
        foreach (var e in results_sellers)
        {
            Console.WriteLine(e.Name, e.Id, e.Type, e.Age);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜