2014-02-20 2 views
1

저는 Linq를 C#으로 XML에 사용하기 시작했습니다. 나는 책에 관한 정보를 담고있는 XML 파일을 가지고있다.XDocument 읽기 하위 요소

<?xml version="1.0"?> 
<catalog> 
    <book id="bk112"> 
     <author>Galos, Mike</author> 
     <title>Visual Studio 7: A Comprehensive Guide</title> 
     <genre>Computer</genre> 
     <price>49.95</price> 
     <publish_date>2001-04-16</publish_date> 
     <description>Microsoft Visual Studio 7 is explored in depth, 
     looking at how Visual Basic, Visual C++, C#, and ASP+ are 
     integrated into a comprehensive development 
     environment.</description> 
    </book> 
</catalog> 

나는 나 저자의 목록과 XML 파일에서 도서 목록 얻을 수 있도록 코드를 작성하는 관리했습니다 :

public List<string> GetBooks() 
{ 
    XDocument document = XDocument.Load(XMLFileLocation); 

    var query = from t in document.Descendants("title") 
       select t.Value; 

    return query.ToList<string>(); 
} 

XML 파일은이 구조를 가지고

그러나 특정 책에 대한 정보를 얻을 수있는 방법을 만드는 방법을 어떻게 진행해야할지 모르겠습니다. 예 :

GetBookAuthor("MyBook"); 

어떻게하면됩니까?

답변

4

XDocument를 고수하고 싶다면 다음과 같은 간단한 방법이 있습니다. 책 이름으로 저자를 얻을 :

public static string GetBookAuthor(XDocument xDoc, string title) 
{ 
    return xDoc.Root 
     .Elements("book") 
     .First(b => b.Element("title").Value == title) 
     .Element("author") 
     .Value; 
} 

내가 객체 지향 접근 방식 좋을 것 그러나 :

왜 저자와 제목 특성을 가진 예약 클래스를 만들지을, 당신은 GetBookAuthor 방법이 필요하지 않습니다 ?

public static Book GetBook(List<Book> bookList, string title) 
{ 
    return bookList.First(b => b.Title == title); 
} 

을 그리고 저자 속성에 액세스 :

public static List<Book> GetBooks() 
{ 
    XDocument document = XDocument.Load(xmlFile); 

    var query = from t in document.Root.Elements("book") 
       select new Book() 
       { 
        Author = t.Element("author").Value, 
        Title = t.Element("title").Value 
       }; 

    return query.ToList(); 
} 

그런 다음 이름으로 책 객체를 반환 할 수 있습니다

var bookList = GetBooks() 
var author = GetBook(bookList, "MyBook").Author; 

public class Book 
{ 
    public string Title { get; set; } 
    public string Author { get; set; } 
    // other Book properties ... 
} 

주소록 개체의 목록을 얻으려면

저자가 더 많은 경우 복잡한 요소가 있으면 작성자 클래스도 만들 수 있습니다.

2

당신은 ID으로 검색 할 경우

var author = document.Descendans("book") 
    .Where(x => (string)x.Attribute("id") == id) 
    .Select(x => (string)x.Element("author")) 
    .FirstOrDefault(); 

당신이 Title으로 검색 할 경우

var author = document.Descendans("book") 
    .Where(x => (string)x.Element("title") == title) 
    .Select(x => (string)x.Element("author")) 
    .FirstOrDefault(); 

null을 확인하고 작성자 이름 반환 :

if(author != null) 
    return author;