using System.Collections.Generic;
public static void Main()
var doc = XDocument.Load("http://www.w3schools.com/xpath/books.xml");
foreach (var elem in doc.XPathSelectElements("//book/title"))
Console.WriteLine("{0} ({1})", elem.Value, elem.Attribute("lang").Value);
Console.WriteLine("\n1. 가격이 낮은 순서부터 오름차순으로 책의 이름, 카테고리를 출력하시오.");
doc.XPathSelectElements("//book").OrderBy(x=>Convert.ToDouble(x.Element("price").Value)).ToList().ForEach(y=>Console.WriteLine("{0} ({1})", y.Element("title").Value, y.Attribute("category").Value));
Console.WriteLine("\n2. 가장 책이 많이 포함되어 있는 카테고리를 출력하시오.");
Console.WriteLine("{0}", doc.XPathSelectElements("//book").Select(x=>x.Attribute("category").Value).GroupBy(x=>x).OrderByDescending(x=>x.Count()).First().First());
Console.WriteLine("\n3. 저자 중 가장 이름이 긴 저자는 어떤 책을썼는지 출력하시오.");
Console.WriteLine("{0}", doc.XPathSelectElements("//book").OrderByDescending(x=>x.Elements("author").Max(y=>y.Value.Length)).First().Element("title").Value);
Console.WriteLine("\n4. Harry Porter는 1997년, 후속작(Harry Porter 2)은 1998년 같은 가격으로 출판되었다. 이 사실을 반영한 XML을 출력하시오.");
var tempX = doc.XPathSelectElements("//book").First(x=>x.Element("title").Value.Equals("Harry Potter"));
tempX.Element("year").Value = "1997";
var nextX = new XElement(tempX);
nextX.Element("title").Value = "Harry Potter 2";
nextX.Element("year").Value = "1998";
tempX.AddAfterSelf(nextX);
Console.WriteLine(doc.ToString());
Console.WriteLine("\n5. WEB 카테고리 이외의 모든 책은 삭제한 다음 결과 XML을 출력하시오.");
doc.XPathSelectElements("//book").Where(x=>!x.Attribute("category").Value.Equals("WEB")).Remove();
Console.WriteLine(doc.ToString());