posted by 써니루루 2007. 3. 26. 10:50

읽어들일 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>


Xml Node를 XPath를 이용해서 선택하는 예제이다.

예제에서는 kind가 '컴퓨터'인 node를 선택하는 예제코드를 보여준다.



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

using System.Xml;

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

            string xPath = "//booklist/book/title[../@kind='컴퓨터']";
            XmlNodeList nodeList = xDoc.SelectNodes(xPath);

            for (int i = 0; i < nodeList.Count; i++)
            {
                string title = nodeList[i].InnerText;
                Console.WriteLine(title);
            }
        }
    }
}


ref. .NET 닷넷 개발자를 위한 XML p.564