2017-05-19 4 views
-1

C# xmlreader 클래스를 사용하여 책 ID "bk101"의 작성자 및 제목 값을 읽으려는이 XML 파일이 있습니다. 나는 그 특별한 이드의 저자와 직함의 가치를 얻을 수 없다.C# xmlreader 클래스를 사용하여 XML의 특정 요소 값을 얻는 방법

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
     <author>Gambardella, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
    </book> 
    <book id="bk102"> 
     <author>Ralls, Kim</author> 
     <title>Midnight Rain</title> 
     <genre>Fantasy</genre> 
     <price>5.95</price> 
     <publish_date>2000-12-16</publish_date> 
     <description>A former architect battles corporate zombies, 
     an evil sorceress, and her own childhood to become queen 
     of the world.</description> 
    </book> 
    <book id="bk103"> 
     <author>Corets, Eva</author> 
     <title>Maeve Ascendant</title> 
     <genre>Fantasy</genre> 
     <price>5.95</price> 
     <publish_date>2000-11-17</publish_date> 
     <description>After the collapse of a nanotechnology 
     society in England, the young survivors lay the 
     foundation for a new society.</description> 
    </book> 
    <book id="bk104"> 
     <author>Corets, Eva</author> 
     <title>Oberon's Legacy</title> 
     <genre>Fantasy</genre> 
     <price>5.95</price> 
     <publish_date>2001-03-10</publish_date> 
     <description>In post-apocalypse England, the mysterious 
     agent known only as Oberon helps to create a new life 
     for the inhabitants of London. Sequel to Maeve 
     Ascendant.</description> 
    </book> 
    <book id="bk105"> 
     <author>Corets, Eva</author> 
     <title>The Sundered Grail</title> 
     <genre>Fantasy</genre> 
     <price>5.95</price> 
     <publish_date>2001-09-10</publish_date> 
     <description>The two daughters of Maeve, half-sisters, 
     battle one another for control of England. Sequel to 
     Oberon's Legacy.</description> 
    </book> 
    <book id="bk106"> 
     <author>Randall, Cynthia</author> 
     <title>Lover Birds</title> 
     <genre>Romance</genre> 
     <price>4.95</price> 
     <publish_date>2000-09-02</publish_date> 
     <description>When Carla meets Paul at an ornithology 
     conference, tempers fly as feathers get ruffled.</description> 
    </book> 
    <book id="bk107"> 
     <author>Thurman, Paula</author> 
     <title>Splish Splash</title> 
     <genre>Romance</genre> 
     <price>4.95</price> 
     <publish_date>2000-11-02</publish_date> 
     <description>A deep sea diver finds true love twenty 
     thousand leagues beneath the sea.</description> 
    </book> 
    <book id="bk108"> 
     <author>Knorr, Stefan</author> 
     <title>Creepy Crawlies</title> 
     <genre>Horror</genre> 
     <price>4.95</price> 
     <publish_date>2000-12-06</publish_date> 
     <description>An anthology of horror stories about roaches, 
     centipedes, scorpions and other insects.</description> 
    </book> 
    <book id="bk109"> 
     <author>Kress, Peter</author> 
     <title>Paradox Lost</title> 
     <genre>Science Fiction</genre> 
     <price>6.95</price> 
     <publish_date>2000-11-02</publish_date> 
     <description>After an inadvertant trip through a Heisenberg 
     Uncertainty Device, James Salway discovers the problems 
     of being quantum.</description> 
    </book> 
    <book id="bk110"> 
     <author>O'Brien, Tim</author> 
     <title>Microsoft .NET: The Programming Bible</title> 
     <genre>Computer</genre> 
     <price>36.95</price> 
     <publish_date>2000-12-09</publish_date> 
     <description>Microsoft's .NET initiative is explored in 
     detail in this deep programmer's reference.</description> 
    </book> 
    <book id="bk111"> 
     <author>O'Brien, Tim</author> 
     <title>MSXML3: A Comprehensive Guide</title> 
     <genre>Computer</genre> 
     <price>36.95</price> 
     <publish_date>2000-12-01</publish_date> 
     <description>The Microsoft MSXML3 parser is covered in 
     detail, with attention to XML DOM interfaces, XSLT processing, 
     SAX and more.</description> 
    </book> 
    <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> 
+2

"XmlReader 클래스 사용"이라고 말씀하셨습니다. 정말로이 클래스를 사용해야합니까, 아니면 다른 사람들을 인식하고 있지 않습니까 (예 : XElement)? –

+0

@ThomasD. 묻습니다, 왜 XmlReader를 사용하고 싶습니까? 문서별로 XmlReader '는 XML 데이터에 대한 빠른 캐시되지 않은 순방향 전용 액세스를 제공하는 판독기를 나타냅니다. 루트 안의 모든 노드를 실제로 방문하려는 경우에만 이와 같은 것을 사용해야합니다. 귀하가 궁금한 점에 대해 XDocument와 같은 XPath가 훨씬 더 합리적입니다. –

+0

실제로 나는 다른 method.If 다른 method.If 모르겠으로 XmlReader 클래스를 사용하여이 질문을 해결하기 시작 이미 시작했다. –

답변

1

나는 당신이 코드

using (var inFile = new FileStream(path, FileMode.Open)) 
    { 
     using (var reader = new XmlTextReader(inFile)) 
     { 
      while (reader.Read()) 
      { 

         if (reader.NodeType == XmlNodeType.Element && reader.Name == "book" && reader.GetAttribute(0) == "bk103") 
         { 


         } 

       } 
      } 
     } 
    } 
+0

그 후에 책의 저자와 제목의 가치를 읽는 방법은? –

0

이 간단한 구현 한 다음 사용할 수의 XMLReader 클래스를 사용하려는 경우 XML을 technique.However에 대한 LINQ를 사용할 수 있다고 생각합니다 (물론, 개선 될 수있다) :

 bool isFoundId = false; 
     string title = string.Empty; 
     string author = string.Empty; 

     using (var str = File.OpenRead("data.xml")) 
     { 
      using (XmlReader reader = new XmlTextReader(str)) 
      { 
       while (reader.Read()) 
       { 
        if (reader.Name == "book") 
        { 
         var v = reader.GetAttribute("id"); 
         if (v == "bk101") 
         { 
          isFoundId = true; 
         } 
         else if (isFoundId) 
         { 
          break; 
         } 
        } 
        if (isFoundId && reader.Name == "title") 
        { 
         title = reader.ReadElementContentAsString(); 
        } 
        if (isFoundId && reader.Name == "author") 
        { 
         author = reader.ReadElementContentAsString(); 
        } 
       } 
      } 
     } 
0

이렇게하면 XPath에서이를 수행 할 수 있습니다. 귀하의 XML이 파일에 있다고 가정했지만 유효한 XML 문자열을 XDocument.Parse 메서드에 전달할 수 있습니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Xml.Linq; 
using System.Xml.XPath; 

namespace StackOverflow 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string catalog = System.IO.File.ReadAllText("catalog.xml"); 

      System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Parse(catalog); 

      var targetBook = xdoc.XPathSelectElement("//catalog/book[@id='bk101']"); 
      var targetBookTitle = targetBook.XPathSelectElement("title").Value; 
      var targetBookAuthor = targetBook.XPathSelectElement("author").Value; 

      Console.Write($"{ targetBookTitle} - { targetBookAuthor}"); 
      Console.Read(); 

     } 
    } 
} 
0

거대한 xml 파일의 경우 xmlreader가 가장 좋습니다. 이것이 내가 가장 좋은 해결책이라고 생각하는 것입니다. 그것은 xmlreader와 xml linq의 조합을 사용합니다. 당신이 매우 큰 XML 문서를하지 않는 한

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     public static void Main(string[] args) 
     { 
      new Book(FILENAME); 
     } 
    } 
    public class Book 
    { 
     public static List<Book> books = new List<Book>(); 

     string id { get; set; } 
     string title { get; set; } 
     string author { get; set; } 

     public Book() { } 
     public Book(string filename) 
     { 
      XmlReader reader = XmlReader.Create(filename); 

      while (!reader.EOF) 
      { 
       if (reader.Name != "book") 
       { 
        reader.ReadToFollowing("book"); 
       } 
       if (!reader.EOF) 
       { 
        Book newBook = new Book(); 
        books.Add(newBook); 

        XElement xmlBook = (XElement)XElement.ReadFrom(reader); 
        newBook.id = (string)xmlBook.Attribute("id"); 
        newBook.author = (string)xmlBook.Element("author"); 
        newBook.title = (string)xmlBook.Element("title"); 
       } 
      } 
     } 
    } 
} 
0

같이, XML에 LINQ를 사용하는 것이 접근 할 수있는 가장 쉬운 방법을 암시했다. 깨끗하고 단순합니다.

var query = 
    from book in doc.Descendants("book") 
    where (string) book.Attribute("id") == "bk101" 
    select new 
    { 
     Author = (string) book.Element("author"), 
     Title = (string) book.Element("title") 
    }; 

var result = query.Single(); 

데모는 this fiddle을 참조하십시오.

관련 문제