프로그래밍 기술/XML.NET

[XML.NET] 18.XmlReader 개체로 데이터 분석(Attribute 읽기)

언제나휴일 2016. 4. 18. 13:20
반응형

XmlReader 개체로 데이터 분석(Attribute 읽기)

 

 XmlReader 클래스는 요소의 특성을 읽기 위해 6가지 메서드와 3가지 속성과 인덱서을 제공합니다. 먼저 이들의 역할과 원형을 살펴봅시다.

 

 특성 값을 얻어올 때 GetAttribute 메서드를 이용합니다.

public string GetAttribute (int i); //i는 인덱스

public string GetAttribute (string name);

public string GetAttribute (string name, string ns_uri);

 

 XmlReader 개체의 현재 위치를 지정한 특성으로 이동할 때 MoveToAttribute 메서드를 이용합니다.

public void MoveToAttribute (int i); //i는 인덱스

public void MoveToAttribute (string name);

public void MoveToAttribute (string name, string ns);

 

 현재 특성 노드를 포함하는 요소로 이동할 때 MoveToElement 메서드를 이용합니다.

public bool MoveToElement ( );

 

 첫 번째 특성으로 이동할 때 MoveToFirstAttribute 메서드를 이용합니다.

public bool MoveToFirstAttribute ( );

 

 다음 특성으로 이동할 때 MoveToNextAttribute 메서드를 이용합니다.

public bool MoveToNextAttribute ( );

 

 특성 값을 분석할 때는 ReadAttributeValue 메서드를 이용합니다.

public bool ReadAttributeValue ( );

 

 현재 노드의 특성 개수를 얻어올 때는 AttributeCount 속성을 이용합니다.

public int AttributeCount { get; }

 

 현재 노드에 특성이 있는지 확인할 때는 HasAttributes 속성을 이용합니다.

public bool HasAttributes { get; }

 

 현재 노드가 유효성 검사에 사용할 DTD나 스키마에 정의한 기본값에서 생성한 값을 가진 특성인지 확인할 때는 IsDefault 속성을 사용합니다.

public bool IsDefault { get; }

 

 특성의 값을 얻어올 때 인덱서를 사용할 수 있습니다.

public string this[int i] { get; } //i:인덱스

public string this[string name] { get; }

public string this[string name, string ns_uri] { get; }

 

 

 다음처럼 XML 문서 파일 "data.xml"이 있을 때 간단하게 XmlReader 개체로 특성 읽기에 관한 예제 코드를 살펴봅시다.

 

data.xml


<?xml version="1.0" encoding="utf-8"?>

<books category=".NET">

  <book title="XML.NET" price="12000" count="50"/>

  <book title="ADO.NET" price="15000" count="60"/>

</books>

[문서] data.xml 문서 내용

 

 예제에서는 먼저 "data.xml" 문서 파일을 인자로 XmlReader 개체를 생성합니다. 그리고 XmlReader 개체로 읽기 작업을 반복하고 현재 위치의 노드에 대한 처리를 하는 구조로 작성하였습니다.

 

 현재 위치에 있는 노드가 "books" 시작 요소일 때는 특성이 있는지 HasAttributes로 확인한 후에 categrory 특성 정보를 읽어와서 콘솔 화면에 출력합니다.

if (reader.HasAttributes)

{

        string category = reader.GetAttribute("category");

        Console.WriteLine("카테고리:{0}", category);

     }

 

 

 현재 위치에 있는 노드가 "book" 시작 요소일 때는 AttributeCount 속성을 이용하여 특성 개수를  얻어온 후에 for문에서 각 인덱스에 있는 특성을 콘솔 화면에 출력합니다. XmlReader 개체가 정방향으로만 이동 가능하다고 했는데 XmlReader 개체의 속성을 사용한다고 해서 위치가 변하지 않습니다.

int attr_cnt=reader.AttributeCount;

for (int i = 0; i < attr_cnt; i++)

{

    Console.Write("{0} ", reader[i]);

}

 

 그리고 또 다른 방법으로 GetAttribute 메서드에 원하는 특성 항목을 얻어와서 콘솔화면에 출력합니다. 마찬가지로 GetAttribute 메서드를 호출하여도 XmlReader 개체의 위치는 변하지 않습니다.

string title = reader.GetAttribute("title");

     string price = reader.GetAttribute("price");

     int count = int.Parse(reader.GetAttribute("count"));

     Console.WriteLine("도서명:{0} 가격:{1} 보유개수:{2}", title, price, count);

 

 

Program.cs


static void Main(string[] args)

{

    XmlReader reader = XmlReader.Create("data.xml");

    while (reader.Read())

    {

        if (reader.IsStartElement("books"))

        {

            if (reader.HasAttributes)

            {

                string category = reader.GetAttribute("category");

                Console.WriteLine("카테고리:{0}", category);

            }

        }

        if (reader.IsStartElement("book"))

        {

            int attr_cnt=reader.AttributeCount;

            for (int i = 0; i < attr_cnt; i++)

            {

                Console.Write("{0} ", reader[i]);

            }

            Console.WriteLine();

            string title = reader.GetAttribute("title");

            string price = reader.GetAttribute("price");

            int count = int.Parse(reader.GetAttribute("count"));

            Console.WriteLine("도서명:{0} 가격:{1} 보유개수:{2}", title, price, count);

        }

    }

}

[소스] XmlReader 개체로 특성 읽기 예제 코드

 

XmlReader 개체로 특성 읽기 예제 실행 화면

[그림] 실행 화면

반응형