2011-01-17 6 views
0

다음과 같은 XML 스키마가 있다고 가정 해 보겠습니다.구조체에 직접 저장하는 LINQ를 사용하는 C# XML 구문 분석

<root> 
    <version>2.0</version> 
    <type>fiction</type> 
    <chapters> 
     <chapter>1</chapter> 
     <title>blah blah</title> 
    </chapter> 
    <chapters> 
     <chapter>2</chapter> 
     <title>blah blah</title> 
    </chapters> 
</root> 

XML에서 반복되지 않고 LINQ를 사용하여 구조체에 직접 저장하는 요소를 파싱 할 가능성이 있습니까?

예를 들어 "version"과 "type"에 대해 이렇게 할 수 있습니까?

//setup structs 
Book book = new Book(); 
book.chapter = new Chapter(); 

//use LINQ to parse the xml 
var bookData = from b in xmlDoc.Decendants("root") 
       select new 
       { 
        book.version = b.Element("version").Value, 
        book.type = b.Element("type").Value 
       }; 

//then for "chapters" since I know there are multiple I can do: 
var chapterData = from c in xmlDoc.Decendants("root" 
        select new 
        { 
        chapter = c.Element("chapters") 
        }; 

foreach (var ch in chapterData) 
{ 
    book.chapter.Add(getChapterData(ch.chapter)); 
} 
+0

변경 가능한 구조체를 사용하지 마십시오. –

+0

왜 확장 할 수 있습니까? 나는 코딩 실력을 향상시키기 위해 모든 노력을 기울이고 있습니다. – Luke

+1

악의적 인 변경 가능한 구조체에 대한 기본 개요 : http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil –

답변

2

이 같은 일을 할 수있는, 단일 지점에서 XML을 구문 분석 할 수 있어야한다. 이 답변의 이익을 위해, 우리는이

Book book = new Book 
{ 
    Version = xmlDoc.Root.Element("version").Value, 
    Type = xmlDoc.Root.Element("type").Value, 
    Chapters = (from chapter in xmlDoc.Descendants("chapters") 
       select new Chapter 
       { 
        Number = (int)chapter.Element("chapter"), 
        Title = chapter.Element("title").Value 
       }).ToList() 
}; 

참고 할 수있는 Book 객체를 생성하기 위해 XML을 사용하여 다음

class Book 
{ 
    public string Version { get; set; } 
    public string Type { get; set; } 
    public List<Chapter> Chapters { get; set; } 
} 

class Chapter 
{ 
    public int Number { get; set; } 
    public string Title { get; set; } 
} 

를 따르고 있습니다의 당신의 BookChapter을 가정 해 봅시다 : 난 structs는 작고 (바람직하게는) 불변이어야하고, 책과 장은 후자 일 수는 있지만 이전과 같지 않을 수 있기 때문에 여기에서 클래스를 사용합니다. 객체가 다른 비 구조체를 캡슐화하고 있다는 사실은 나에게 객체가 구조체가 아니어야 함을 의미합니다.

+0

감사합니다.이 방법을 통해 지갑을 판매 할 수 있습니다. 명목상의 성능 차이가 있습니까? 나는 코드를 물려 받았다. 현재 직렬화 된 구조체를 사용하며 이유가 있는지 궁금합니다. IE의 성능, 또는 그냥 더 잘 몰랐습니다. – Luke