'GetElementByTagName'에 해당되는 글 1건

  1. 2007.03.26 GetElementByTagName을 이용한 Element 선택
posted by 써니루루 2007. 3. 26. 10:29
읽어들일 XML 파일 'booklist.xml'

<?xml version="1.0" encoding="utf-8" ?>
<booklist>
  <book id="b1" kind="컴퓨터">
    <title>기초에서 실무까지 XML</title>
    <author>신민철</author>
    <publisher>프리렉</publisher>
    <price>35000</price>
  </book>
  <book id="b2" kind="소설">
    <title>사랑과 전쟁</title>
    <author>이사랑</author>
    <publisher>전쟁문화사</publisher>
    <price>15000</price>
  </book>
  <book id="b3" kind="잡지">
    <title>마이크로 소프트</title>
    <author>빌 게이츠</author>
    <publisher>마소문화사</publisher>
    <price>20000</price>
  </book>
  <book id="b4" kind="소설">
    <title>액션가면부인 바람났네</title>
    <author>짱구</author>
    <publisher>짱구출판사</publisher>
    <price>12000</price>
  </book>
</booklist>


이번 예제는 Javascript 로 dom을 이용한 분들은 친숙할 getElementByTagName() 메소드를 보게되는 예제이다. 마찬가지로 tag 이름을 가지고 엘리먼트를 선택하는 예제이다.

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

using System.Xml;

namespace CH11
{
    class p560_FindElementByTagName
    {
        static void Main()
        {
            string filePath = @"..\..\booklist.xml";
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(filePath);

            XmlNodeList titleNodeList = xDoc.GetElementsByTagName("title");
            for (int i = 0; i < titleNodeList.Count; i++)
            {
                XmlNode titleNode = titleNodeList[i];
                XmlNodeList childNodeList = titleNode.ChildNodes;
                XmlNode textNode = childNodeList[0];
                string value = textNode.Value;
                Console.WriteLine(value);
            }
        }
    }
}

title 엘리먼트를 찾고 책의 제목을 출력하게되는 예제이다.