XMLDocument 이용한 검색

 

string path = "booklist.xml";

XmlDocument doc = new XmlDocument();

doc.Load(path);

string xPath = "//book/title[../@kind='소설']";

// SelectNodes 메서드는 검색조건에 맞는 개체를 XmlNodeList 반환하고

// SelectSingleNode 메서드는 검색조건에 맞는 단한개의 XmlNode 만을 반환(ID속성일 경우 쓰임)

           

XmlNodeList nodeList = doc.SelectNodes(xPath);

for (int i = 0; i < nodeList.Count; i++)

{

string title = nodeList[i].InnerText;

Console.WriteLine(title);

}


 

XPathDocument 이용한 검색

 // [1]. XPathDocument 생성

XPathDocument xdoc = new XPathDocument("booklist.xml");

// [2]. XPathNavigator 생성 -> XML 데이터를 탐색하고 편집하기 위한 커서모델을 제공한다.

XPathNavigator xPathNavi= xdoc.CreateNavigator();

// [3]. XPathNodeIterator 생성 -> 반복기 역활

XPathNodeIterator xPathIterator = xPathNavi.Select("//booklist/book/title[../@kind='컴퓨터']");

// [4]. kind='컴퓨터' 없을 까지 돈다.

while (xPathIterator.MoveNext())

{

     XPathNavigator navigatorTitle = xPathIterator.Current;

     Console.WriteLine(navigatorTitle.Value);

}  



by 피요히코~ 2009. 2. 25. 13:15