XPathNavigator를 이용해서 Xml 문서를 탐색하고 값을 얻어내는 예제.
특별히 설명될 내용이 없는 간단한 예제이다.
조금 눈 여겨 볼 내용은 XmlDocument를 통해서 생성되는 것이 아닌 XPathDocument를 통해서 XPathNavigator를 생성한다는 점이다.
단순하게 문서를 읽는데에는 XmlDocument나 XDocument를 사용하는 것이 좋으나, xml 파일이 커지거나 xml파일을 일정하게 검색, 변경
할때에는 XPathNavigator를 통해서 검색하는 것이 속도나 코드 면에서 훨씬 좋다.
/****************************** Module Header ******************************\
* Module Name: Program.cs
* Project: CSXPath
* Copyright (c) Microsoft Corporation.
*
* This sample project shows how to use XPathDocument class to load the XML
* file and manipulate. It includes two main parts, XPathNavigator usage and
* XPath Expression usage. The first part shows how to use XPathNavigator to
* navigate through the whole document, read its content. The second part
* shows how to use XPath expression to filter information and select it out.
*
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
* All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace CSXPath
{
class Program
{
static void Main(string[] args)
{
#region Initialize XPathDocument and XPathNavigator
XPathNavigator xPathNavigator;
XPathDocument xPathDoc;
//Navigate through the whole document
//Create a new instance of XPathDocument from a XML file
xPathDoc = new XPathDocument("books.xml");
//Call CreateNavigator method to create a navigator instance
//And we will use this navigator object to navigate through whole document
xPathNavigator = xPathDoc.CreateNavigator();
#endregion
#region Navigate through the document
//Move to the root element
xPathNavigator.MoveToRoot();
//Catalog element is the first children of the root
//Move to catalog element
xPathNavigator.MoveToFirstChild();
//We can know a XML node's type from the NodeType property
//XPathNodeType has Attribute, Element, Namespace and so on
if (xPathNavigator.NodeType == XPathNodeType.Element)
{
//We can know if a Node has child nodes by checking its
//HasChildren property. If it returns true, that node has
//child nodes
if (xPathNavigator.HasChildren == true)
{
//Move to the first child which is our first book nodes
xPathNavigator.MoveToFirstChild();
do
{
//We can know if a node has any attribute by checking
//the HasAttributes property. When this property returns
//true, we can get the specified attribute by calling
//navigator.GetAttribute() method
if (xPathNavigator.HasAttributes == true)
{
Console.WriteLine("Book ID: " + xPathNavigator.GetAttribute("id", ""));
}
//Iterate through a book node's child nodes
//and list all child node information, like
//name, author, price, publish date and so on
if (xPathNavigator.HasChildren)
{
xPathNavigator.MoveToFirstChild();
do
{
Console.Write("\t{0}:\t{1}\r\n", xPathNavigator.Name, xPathNavigator.Value);
} while (xPathNavigator.MoveToNext());
//When all child nodes are reached. The MoveToNext() method returns
//false. Then we need to call MoveToParent to go back to the book level
xPathNavigator.MoveToParent();
}
//Move to the next book element.
} while (xPathNavigator.MoveToNext());
}
}
#endregion
#region Use of XPath Expression
//Use XPath Expression to select out book bk103
//The expression should be "/catalog/book[@id='bk103']"
//@ means to look id attribute and match bk103
Console.WriteLine("Use XPath Expression to select out the book with ID bk103:");
XPathExpression expression = xPathNavigator.Compile("/catalog/book[@id='bk103']");
XPathNodeIterator iterator = xPathNavigator.Select(expression);
//After compile the XPath expression, we can call navigator.Select
//to retrieve the XPathNodeIterator. With this interator, we can loop
//trough the results filtered by the XPath expression
//The following codes print the book bk103's detailed information
while (iterator.MoveNext())
{
XPathNavigator nav = iterator.Current.Clone();
Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
if (nav.HasChildren)
{
nav.MoveToFirstChild();
do
{
Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
} while (nav.MoveToNext());
}
}
//Use XPath to select out all books whose price are more than 10.00
// '[]' means to look into the child node to match the condition "price > 10"
Console.WriteLine("\r\nUse XPath Expression to select out all books whose price are more than 10:");
expression = xPathNavigator.Compile("/catalog/book[price>10]");
iterator = xPathNavigator.Select(expression);
//After getting the iterator, we print title and price for books
//whose price are more than 10
while (iterator.MoveNext())
{
XPathNavigator nav = iterator.Current.Clone();
Console.WriteLine("Book ID: " + nav.GetAttribute("id", ""));
if (nav.HasChildren)
{
nav.MoveToFirstChild();
do
{
if (nav.Name == "title")
{
Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
}
if (nav.Name == "price")
{
Console.Write("\t{0}:\t{1}\r\n", nav.Name, nav.Value);
}
} while (nav.MoveToNext());
}
}
//Use XPath Expression to calculate the average price of all books.
//Here in XPath, we use the sum, div, and count formula.
Console.WriteLine("\r\nUse XPath Expression to calculate the average price of all books:");
expression = xPathNavigator.Compile("sum(/catalog/book/price) div count(/catalog/book/price)");
string averagePrice = xPathNavigator.Evaluate(expression).ToString();
Console.WriteLine("The average price of the books are {0}", averagePrice);
#endregion
#region End. Read a char to exit
Console.WriteLine("Input any key to quit the sample application");
Console.ReadLine();
#endregion
}
}
}
Gambardella, Matthew
XML Developer's Guide
Computer
44.95
2000-10-01
An in-depth look at creating applications
with XML.
Ralls, Kim
Midnight Rain
Fantasy
5.95
2000-12-16
A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.
Corets, Eva
Maeve Ascendant
Fantasy
5.95
2000-11-17
After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.
Corets, Eva
Oberon's Legacy
Fantasy
5.95
2001-03-10
In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.
Corets, Eva
The Sundered Grail
Fantasy
5.95
2001-09-10
The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.
Randall, Cynthia
Lover Birds
Romance
4.95
2000-09-02
When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.
Thurman, Paula
Splish Splash
Romance
4.95
2000-11-02
A deep sea diver finds true love twenty
thousand leagues beneath the sea.
Knorr, Stefan
Creepy Crawlies
Horror
4.95
2000-12-06
An anthology of horror stories about roaches,
centipedes, scorpions and other insects.
Kress, Peter
Paradox Lost
Science Fiction
6.95
2000-11-02
After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.
O'Brien, Tim
Microsoft .NET: The Programming Bible
Computer
36.95
2000-12-09
Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.
O'Brien, Tim
MSXML3: A Comprehensive Guide
Computer
36.95
2000-12-01
The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.
Galos, Mike
Visual Studio 7: A Comprehensive Guide
Computer
49.95
2001-04-16
Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.