The XML Source file is:
- <?xml version="1.0" encoding="GB2312"?>
- <Books>
- <Book genre="Mystery" publicationdate="2001" ISBN="123456789">
- <title>The Case of the Missing Cookie</title>
- <author Country="America">
- <Name>Cookie Monster</Name>
- </author>
- <Price>$9.99</Price>
- </Book>
- <ALFKI />
- <ANATR />
- <ANTON />
- <AROUT />
- <BERGS />
- <ALFKI />
- <ANATR />
- <ANTON />
- <AROUT />
- <BERGS />
- <ALFKI />
- <ANATR />
- <ANTON />
- <AROUT />
- <BERGS />
- </Books>
2. You must add reference for Linq To XML
- using System.Xml.Linq;
3. Select nodes you want, now i will select all the sub nodes which start with character "A".
- XDocument doc = XDocument.Load("d://ddd.xml");
- // build linq query
- var query = from c in doc.Elements("Books").Elements()
- where c.Name.ToString().StartsWith("A")
- select c;
- // visit every element in the query
- foreach (XElement a in query)
- {
- Console.WriteLine(a.Name);
- }
- // in this sentence we can get the total count of the query
- Console.WriteLine("The records count is {0}.",query.Count());
The result is as follows: