XML 데이터 구조 예시
<?xml version="1.0"?>
<library>
<book id="lib001">
<author>김철수</author>
<title>XML 마스터하기</title>
<category>컴퓨터</category>
<price>55.00</price>
<published>2023-05-12</published>
</book>
<book id="lib002">
<author>이영희</author>
<title>.NET 정복</title>
<category>프로그래밍</category>
<price>48.50</price>
<published>2022-11-30</published>
</book>
</library>
XPath 처리 클래스 구조
public class XmlDataExplorer
{
private XPathDocument dataDoc;
private XPathNavigator dataNavigator;
public XmlDataExplorer(string filePath)
{
dataDoc = new XPathDocument(filePath);
dataNavigator = dataDoc.CreateNavigator();
}
}
노드 순회 및 데이터 출력
public void TraverseNodes()
{
dataNavigator.MoveToRoot();
dataNavigator.MoveToFirstChild();
while(dataNavigator.MoveToFirstChild())
{
if(dataNavigator.HasAttributes)
{
Console.WriteLine($"도서 ID: {dataNavigator.GetAttribute("id", "")}");
}
XPathNavigator childNode = dataNavigator.Clone();
childNode.MoveToFirstChild();
do
{
Console.WriteLine($"{childNode.Name}: {childNode.Value}");
}
while(childNode.MoveToNext());
}
}
조건별 노드 검색
public void FindByCriteria(string id)
{
XPathExpression query = dataNavigator.Compile($"/library/book[@id='{id}']");
XPathNodeIterator results = dataNavigator.Select(query);
while(results.MoveNext())
{
XPathNavigator current = results.Current;
Console.WriteLine($"도서 ID: {current.GetAttribute("id", "")}");
Console.WriteLine($"제목: {current.SelectSingleNode("title").Value}");
}
}
가격 기반 필터링
public void FilterByPrice(decimal minPrice)
{
XPathExpression query = dataNavigator.Compile($"/library/book[price > {minPrice}]");
XPathNodeIterator results = dataNavigator.Select(query);
while(results.MoveNext())
{
XPathNavigator current = results.Current;
Console.WriteLine($"제목: {current.SelectSingleNode("title").Value}");
Console.WriteLine($"가격: {current.SelectSingleNode("price").Value}");
}
}
집계 연산 수행
public void CalculatePriceMetrics()
{
XPathExpression avgQuery = dataNavigator.Compile(
"sum(/library/book/price) div count(/library/book/price)");
object avgResult = dataNavigator.Evaluate(avgQuery);
Console.WriteLine($"평균 가격: {avgResult}");
}