XML Readers and Writers General .NET2007/12/17 10:21
작성자: 박종현
작성일: 2007-09-05
출처: http://samples.gotdotnet.com/quickstart ··· ile.aspx
XML Readers and Writers
Read XML from a file
파일에서 XML을 읽는 방법
XmlReader 클래스는 XML 파싱을 제공하는 API 이다.
XmlTextReader는 바이트 스트림들을 핸들하기 위해 디자인된 도구이다.
일반적으로, 당신이 DOM Overhead가 없는 가공되지 않은 Xml 데이터를 읽기를 원한다면 XmlTextReader를 사용한다.
아래는 books.xml 이다.
|
<?xml version="1.0" ?> <bookstore> <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author><price>11.99</price> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <name>Plato</name> </author> <price>9.99</price> </book> </bookstore> |
다음은 이것을 읽어들이는 C#코드이다.
XML파일을 읽기 위해 2가지의 네임스페이스를 추가한다.
|
using System.Xml; using System.Text; |
아래의 코드에서는 XML의 부모 노드 정보만 가져온다.
|
//읽어올 XML 파일을 XmlTextReader 객체에 담는다. XmlTextReader reader = new XmlTextReader( @"D:\wwwroot\Pilot_Web\AboutOnlyXML\books1.xml" ); //출력을 위한 StringBuilder를 인스턴스화 한다. StringBuilder sb = new StringBuilder(); //파일을 읽는다. while(reader.Read()) { //노드가 발견되면 엘리먼트를 읽고, 엘리먼트에 어트리뷰트도 읽어들인다. switch (reader.NodeType) { case XmlNodeType.Element: //노드는 엘리먼트이다. sb.Append("<"+ reader.Name); while (reader.MoveToNextAttribute()); //Read Attribute { sb.Append(" " + reader.Name + "='" + reader.Value + "'"); } sb.Append(">"); break; case XmlNodeType.DocumentType: //노드의 문서타입 sb.Append(reader.NodeType + "<" + reader.Name + ">" + reader.Value); break; } this.lblReadXMLData.Text = sb.ToString(); } |
이것의 출력 결과는 아래와 같다.
|
<bookstore> <book genre='autobiography' publicationdate='1981' ISBN='1-861003-11-0'> <title> <author> <first-name> <last-name> <price> <book genre='novel' publicationdate='1967' ISBN='0-201-63361-2'> <title> <author> <first-name> <last-name> <price> <book genre='philosophy' publicationdate='1991' ISBN='1-861001-57-6'> <title> <author> <name> <price> |
XmlNodeType은 XmlReader 클래스에 의해 의존적이고 리턴된다.
XmlTextReader 클래스는 XmlNodeType인 Document, Documentfragment, Entity, EndEntity 그리고 Notation 노드를 리턴한다.
|
XmlNodeType Enumeration Member |
Description |
|
Attribute |
어트리뷰트. |
|
CDATA |
CDATA 섹션. |
|
Comment |
코멘트 예: <!-- my comment --> 코멘트 노드는 자식 노드를 가질 수 없다. Document, DocumentFragment, Element, and EntityReference nodes의 자식노드에 나타날 수 있다. |
|
Document |
문서객체는 xml 문서 전체의 액세스 제공자, 문서 트리의 루트. Document 노드는 다음의 자식노드 타입을 가진다.: Element (maximum of one), ProcessingInstruction, Comment, and DocumentType. The Document node cannot appear as the child of any node types. |
|
DocumentFragment |
document fragment. DocumentFragment 노드는 다음의 자식노드 타입을 가질 수 있다. : Element, ProcessingInstruction, Comment, Text, CDATASection, and EntityReference. DocumentFragment node는 자식노드타입에 나타날 수 없다. |
|
DocumentType |
Document 타입 선은 <!DOCTYPE> 태그를 사용. 예 XML: <!DOCTYPE ...> DocumentType 노드는 문서타입의 자식노드로 나타날 수 있다. |
|
Element |
엘리먼트 Element, Text, Comment, ProcessingInstruction, CDATA, 그리고 EntityReference. Element 노드는 Document, DocumentFragment, EntityReference, Element nodes들의 자식노드에 나타날 수 있다. |
|
EndElement |
XmlReader가 element의 끝에 다다를 때 리턴되는 값 예 XML: </foo> |
|
EndEntity |
Returned when XmlReader gets to the end of the entity replacement as a result of a call to ResolveEntity. |
|
Entity |
엔티티 선언 |
|
EntityReference |
엔티티참조 |
|
None |
This is returned by the XmlReader if a Read method has not been called. |
|
Notation |
A notation in the document type declaration. |
|
ProcessingInstruction |
A processing instruction (PI). |
|
SignificantWhitespace |
Whitespace between markup in a mixed content model, or whitespace within the xml:space= "preserve" scope. |
|
Text |
The text content of an element. A Text node cannot have any child nodes. The Text node can appear as the child node of the Attribute, DocumentFragment, Element, and EntityReference nodes. |
|
Whitespace |
Whitespace between markup. |
|
XmlDeclaration |
The XML declaration node. |
그럼 이제 books.xml 이 가지는 모든 엘리먼트와 어트리뷰트를 읽어보도록 하겠습니다.
|
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using System.Xml; using System.Text; public partial class AboutOnlyXML_ReadXMLFile : System.Web.UI.Page { private const string document = @"D:\wwwroot\Pilot_Web\AboutOnlyXML\books.xml"; public static void Main() { AboutOnlyXML_ReadXMLFile myReadXmlFileSample = new AboutOnlyXML_ReadXMLFile(); myReadXmlFileSample.Run(document); } public void Run(String args) { XmlTextReader reader = null; try { Console.WriteLine("읽을 파일 {0} ...", args); reader = new XmlTextReader(args); Console.WriteLine("파일 {0} 을 성공적으로 읽었습니다....", args); Console.WriteLine("출력을 시작합니다."); Console.WriteLine(); FormatXml(reader, args); } catch (Exception e) { Console.WriteLine("Failed to read the file {0}", args); Console.WriteLine("Exception: {0}", e.ToString()); } finally { Console.WriteLine(); Console.WriteLine("Processing of the file {0} complete.", args); // Finished with XmlTextReader if (reader != null) reader.Close(); } } private static void FormatXml(XmlReader reader, String filename) { int declarationCount = 0, piCount = 0, docCount = 0, commentCount = 0, elementCount = 0, attributeCount = 0, textCount = 0, whitespaceCount = 0; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: Format(reader, "XmlDeclaration"); declarationCount++; break; case XmlNodeType.ProcessingInstruction: Format(reader, "ProcessingInstruction"); piCount++; break; case XmlNodeType.DocumentType: Format(reader, "DocumentType"); docCount++; break; case XmlNodeType.Comment: Format(reader, "Comment"); commentCount++; break; case XmlNodeType.Element: Format(reader, "Element"); elementCount++; if (reader.HasAttributes) attributeCount += reader.AttributeCount; break; case XmlNodeType.Text: Format(reader, "Text"); textCount++; break; case XmlNodeType.Whitespace: whitespaceCount++; break; } } // Display the Statistics for the file. Console.WriteLine(); Console.WriteLine("Statistics for {0} file", filename); Console.WriteLine(); Console.WriteLine("XmlDeclaration: {0}", declarationCount++); Console.WriteLine("ProcessingInstruction: {0}", piCount++); Console.WriteLine("DocumentType: {0}", docCount++); Console.WriteLine("Comment: {0}", commentCount++); Console.WriteLine("Element: {0}", elementCount++); Console.WriteLine("Attribute: {0}", attributeCount++); Console.WriteLine("Text: {0}", textCount++); Console.WriteLine("Whitespace: {0}", whitespaceCount++); } private static void Format(XmlReader reader, String nodeType) { Console.Write(reader.Depth + " "); Console.Write(reader.AttributeCount + " "); for (int i = 0; i < reader.Depth; i++) { Console.Write('\t'); } Console.Write(reader.Prefix + nodeType + "<" + reader.Name + ">" + reader.Value); if (reader.HasAttributes) { Console.Write(" Attributes:"); for (int j = 0; j < reader.AttributeCount; j++) { Console.Write(" [{0}] " + reader[j], j); } } Console.WriteLine(); } protected void btnReadXML_Click(object sender, EventArgs e) { StringWriter writer = new StringWriter(); Console.SetOut(writer); AboutOnlyXML_ReadXMLFile myReadXmlFileSample = new AboutOnlyXML_ReadXMLFile(); myReadXmlFileSample.Run(Server.MapPath("books.xml")); this.ouput.InnerHtml = writer.ToString(); } } |
출력 결과
|
아래의 버튼을 클릭하면 XML 파일을 읽어옵니다. 파일에서 읽은 데이터를 출력합니다.... 읽을 파일 D:\wwwroot\Pilot_Web\AboutOnlyXML\books.xml ... 파일 D:\wwwroot\Pilot_Web\AboutOnlyXML\books.xml 을 성공적으로 읽었습니다.... Processing ... 0 1 XmlDeclaration<xml>version="1.0" Attributes: [0] 1.0 0 0 Element<bookstore> 1 3 Element<book> Attributes: [0] autobiography [1] 1981 [2] 1-861003-11-0 2 0 Element<title> 3 0 Text<>The Autobiography of Benjamin Franklin 2 0 Element<author> 3 0 Element<first-name> 4 0 Text<>Benjamin 3 0 Element<last-name> 4 0 Text<>Franklin 2 0 Element<price> 3 0 Text<>8.99 1 3 Element<book> Attributes: [0] novel [1] 1967 [2] 0-201-63361-2 2 0 Element<title> 3 0 Text<>The Confidence Man 2 0 Element<author> 3 0 Element<first-name> 4 0 Text<>Herman 3 0 Element<last-name> 4 0 Text<>Melville 2 0 Element<price> 3 0 Text<>11.99 1 3 Element<book> Attributes: [0] philosophy [1] 1991 [2] 1-861001-57-6 2 0 Element<title> 3 0 Text<>The Gorgias 2 0 Element<author> 3 0 Element<name> 4 0 Text<>Plato 2 0 Element<price> 3 0 Text<>9.99 Statistics for D:\wwwroot\Pilot_Web\AboutOnlyXML\books.xml file XmlDeclaration: 1 ProcessingInstruction: 0 DocumentType: 0 Comment: 0 Element: 18 Attribute: 9 Text: 11 Whitespace: 25 Processing of the file D:\wwwroot\Pilot_Web\AboutOnlyXML\books.xml complete. |
'General .NET' 카테고리의 다른 글
| XML in the .NET Framework (0) | 2007/12/17 |
|---|---|
| XML Data (0) | 2007/12/17 |
| XML Readers and Writers (0) | 2007/12/17 |
| C#으로 XML문서 생성하기 (0) | 2007/12/17 |
| String.Format 메서드 (0) | 2007/12/17 |
| Microsoft .NET Framework 3.0 Programming Model (0) | 2007/12/17 |
