XPathNavigator를 이용해서 Xml 문서를 탐색하고 값을 얻어내는 예제.
특별히 설명될 내용이 없는 간단한 예제이다.
조금 눈 여겨 볼 내용은 XmlDocument를 통해서 생성되는 것이 아닌 XPathDocument를 통해서 XPathNavigator를 생성한다는 점이다.
단순하게 문서를 읽는데에는 XmlDocument나 XDocument를 사용하는 것이 좋으나, xml 파일이 커지거나 xml파일을 일정하게 검색, 변경
할때에는 XPathNavigator를 통해서 검색하는 것이 속도나 코드 면에서 훨씬 좋다.
특별히 설명될 내용이 없는 간단한 예제이다.
조금 눈 여겨 볼 내용은 XmlDocument를 통해서 생성되는 것이 아닌 XPathDocument를 통해서 XPathNavigator를 생성한다는 점이다.
단순하게 문서를 읽는데에는 XmlDocument나 XDocument를 사용하는 것이 좋으나, xml 파일이 커지거나 xml파일을 일정하게 검색, 변경
할때에는 XPathNavigator를 통해서 검색하는 것이 속도나 코드 면에서 훨씬 좋다.
001.
/****************************** Module Header ******************************\
002.
* Module Name: Program.cs
003.
* Project: CSXPath
004.
* Copyright (c) Microsoft Corporation.
005.
*
006.
* This sample project shows how to use XPathDocument class to load the XML
007.
* file and manipulate. It includes two main parts, XPathNavigator usage and
008.
* XPath Expression usage. The first part shows how to use XPathNavigator to
009.
* navigate through the whole document, read its content. The second part
010.
* shows how to use XPath expression to filter information and select it out.
011.
*
012.
* This source is subject to the Microsoft Public License.
013.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
014.
* All other rights reserved.
015.
*
016.
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
017.
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
018.
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
019.
\***************************************************************************/
020.
021.
using
System;
022.
using
System.Collections.Generic;
023.
using
System.Linq;
024.
using
System.Text;
025.
using
System.Xml;
026.
using
System.Xml.XPath;
027.
028.
029.
namespace
CSXPath
030.
{
031.
class
Program
032.
{
033.
static
void
Main(
string
[] args)
034.
{
035.
#region Initialize XPathDocument and XPathNavigator
036.
037.
XPathNavigator xPathNavigator;
038.
XPathDocument xPathDoc;
039.
040.
//Navigate through the whole document
041.
//Create a new instance of XPathDocument from a XML file
042.
xPathDoc =
new
XPathDocument(
"books.xml"
);
043.
044.
//Call CreateNavigator method to create a navigator instance
045.
//And we will use this navigator object to navigate through whole document
046.
xPathNavigator = xPathDoc.CreateNavigator();
047.
048.
#endregion
049.
050.
#region Navigate through the document
051.
052.
//Move to the root element
053.
xPathNavigator.MoveToRoot();
054.
//Catalog element is the first children of the root
055.
//Move to catalog element
056.
xPathNavigator.MoveToFirstChild();
057.
//We can know a XML node's type from the NodeType property
058.
//XPathNodeType has Attribute, Element, Namespace and so on
059.
if
(xPathNavigator.NodeType == XPathNodeType.Element)
060.
{
061.
//We can know if a Node has child nodes by checking its
062.
//HasChildren property. If it returns true, that node has
063.
//child nodes
064.
if
(xPathNavigator.HasChildren ==
true
)
065.
{
066.
//Move to the first child which is our first book nodes
067.
xPathNavigator.MoveToFirstChild();
068.
do
069.
{
070.
//We can know if a node has any attribute by checking
071.
//the HasAttributes property. When this property returns
072.
//true, we can get the specified attribute by calling
073.
//navigator.GetAttribute() method
074.
if
(xPathNavigator.HasAttributes ==
true
)
075.
{
076.
Console.WriteLine(
"Book ID: "
+ xPathNavigator.GetAttribute(
"id"
,
""
));
077.
}
078.
079.
//Iterate through a book node's child nodes
080.
//and list all child node information, like
081.
//name, author, price, publish date and so on
082.
if
(xPathNavigator.HasChildren)
083.
{
084.
xPathNavigator.MoveToFirstChild();
085.
do
086.
{
087.
Console.Write(
"\t{0}:\t{1}\r\n"
, xPathNavigator.Name, xPathNavigator.Value);
088.
}
while
(xPathNavigator.MoveToNext());
089.
//When all child nodes are reached. The MoveToNext() method returns
090.
//false. Then we need to call MoveToParent to go back to the book level
091.
xPathNavigator.MoveToParent();
092.
}
093.
//Move to the next book element.
094.
}
while
(xPathNavigator.MoveToNext());
095.
}
096.
}
097.
098.
#endregion
099.
100.
#region Use of XPath Expression
101.
102.
//Use XPath Expression to select out book bk103
103.
//The expression should be "/catalog/book[@id='bk103']"
104.
//@ means to look id attribute and match bk103
105.
Console.WriteLine(
"Use XPath Expression to select out the book with ID bk103:"
);
106.
XPathExpression expression = xPathNavigator.Compile(
"/catalog/book[@id='bk103']"
);
107.
XPathNodeIterator iterator = xPathNavigator.Select(expression);
108.
109.
//After compile the XPath expression, we can call navigator.Select
110.
//to retrieve the XPathNodeIterator. With this interator, we can loop
111.
//trough the results filtered by the XPath expression
112.
//The following codes print the book bk103's detailed information
113.
114.
while
(iterator.MoveNext())
115.
{
116.
XPathNavigator nav = iterator.Current.Clone();
117.
Console.WriteLine(
"Book ID: "
+ nav.GetAttribute(
"id"
,
""
));
118.
if
(nav.HasChildren)
119.
{
120.
nav.MoveToFirstChild();
121.
do
122.
{
123.
Console.Write(
"\t{0}:\t{1}\r\n"
, nav.Name, nav.Value);
124.
}
while
(nav.MoveToNext());
125.
}
126.
}
127.
128.
129.
//Use XPath to select out all books whose price are more than 10.00
130.
// '[]' means to look into the child node to match the condition "price > 10"
131.
Console.WriteLine(
"\r\nUse XPath Expression to select out all books whose price are more than 10:"
);
132.
expression = xPathNavigator.Compile(
"/catalog/book[price>10]"
);
133.
iterator = xPathNavigator.Select(expression);
134.
135.
//After getting the iterator, we print title and price for books
136.
//whose price are more than 10
137.
while
(iterator.MoveNext())
138.
{
139.
XPathNavigator nav = iterator.Current.Clone();
140.
Console.WriteLine(
"Book ID: "
+ nav.GetAttribute(
"id"
,
""
));
141.
if
(nav.HasChildren)
142.
{
143.
nav.MoveToFirstChild();
144.
do
145.
{
146.
if
(nav.Name ==
"title"
)
147.
{
148.
Console.Write(
"\t{0}:\t{1}\r\n"
, nav.Name, nav.Value);
149.
}
150.
if
(nav.Name ==
"price"
)
151.
{
152.
Console.Write(
"\t{0}:\t{1}\r\n"
, nav.Name, nav.Value);
153.
}
154.
}
while
(nav.MoveToNext());
155.
}
156.
}
157.
158.
//Use XPath Expression to calculate the average price of all books.
159.
//Here in XPath, we use the sum, div, and count formula.
160.
Console.WriteLine(
"\r\nUse XPath Expression to calculate the average price of all books:"
);
161.
expression = xPathNavigator.Compile(
"sum(/catalog/book/price) div count(/catalog/book/price)"
);
162.
string
averagePrice = xPathNavigator.Evaluate(expression).ToString();
163.
Console.WriteLine(
"The average price of the books are {0}"
, averagePrice);
164.
165.
166.
#endregion
167.
168.
#region End. Read a char to exit
169.
170.
Console.WriteLine(
"Input any key to quit the sample application"
);
171.
Console.ReadLine();
172.
173.
#endregion
174.
}
175.
}
176.
}
001.
<!--?xml version="1.0"?-->
002.
<
catalog
>
003.
<
book
id
=
"bk101"
>
004.
<
author
>Gambardella, Matthew</
author
>
005.
<
title
>XML Developer's Guide</
title
>
006.
<
genre
>Computer</
genre
>
007.
<
price
>44.95</
price
>
008.
<
publish_date
>2000-10-01</
publish_date
>
009.
<
description
>
010.
An in-depth look at creating applications
011.
with XML.
012.
</
description
>
013.
</
book
>
014.
<
book
id
=
"bk102"
>
015.
<
author
>Ralls, Kim</
author
>
016.
<
title
>Midnight Rain</
title
>
017.
<
genre
>Fantasy</
genre
>
018.
<
price
>5.95</
price
>
019.
<
publish_date
>2000-12-16</
publish_date
>
020.
<
description
>
021.
A former architect battles corporate zombies,
022.
an evil sorceress, and her own childhood to become queen
023.
of the world.
024.
</
description
>
025.
</
book
>
026.
<
book
id
=
"bk103"
>
027.
<
author
>Corets, Eva</
author
>
028.
<
title
>Maeve Ascendant</
title
>
029.
<
genre
>Fantasy</
genre
>
030.
<
price
>5.95</
price
>
031.
<
publish_date
>2000-11-17</
publish_date
>
032.
<
description
>
033.
After the collapse of a nanotechnology
034.
society in England, the young survivors lay the
035.
foundation for a new society.
036.
</
description
>
037.
</
book
>
038.
<
book
id
=
"bk104"
>
039.
<
author
>Corets, Eva</
author
>
040.
<
title
>Oberon's Legacy</
title
>
041.
<
genre
>Fantasy</
genre
>
042.
<
price
>5.95</
price
>
043.
<
publish_date
>2001-03-10</
publish_date
>
044.
<
description
>
045.
In post-apocalypse England, the mysterious
046.
agent known only as Oberon helps to create a new life
047.
for the inhabitants of London. Sequel to Maeve
048.
Ascendant.
049.
</
description
>
050.
</
book
>
051.
<
book
id
=
"bk105"
>
052.
<
author
>Corets, Eva</
author
>
053.
<
title
>The Sundered Grail</
title
>
054.
<
genre
>Fantasy</
genre
>
055.
<
price
>5.95</
price
>
056.
<
publish_date
>2001-09-10</
publish_date
>
057.
<
description
>
058.
The two daughters of Maeve, half-sisters,
059.
battle one another for control of England. Sequel to
060.
Oberon's Legacy.
061.
</
description
>
062.
</
book
>
063.
<
book
id
=
"bk106"
>
064.
<
author
>Randall, Cynthia</
author
>
065.
<
title
>Lover Birds</
title
>
066.
<
genre
>Romance</
genre
>
067.
<
price
>4.95</
price
>
068.
<
publish_date
>2000-09-02</
publish_date
>
069.
<
description
>
070.
When Carla meets Paul at an ornithology
071.
conference, tempers fly as feathers get ruffled.
072.
</
description
>
073.
</
book
>
074.
<
book
id
=
"bk107"
>
075.
<
author
>Thurman, Paula</
author
>
076.
<
title
>Splish Splash</
title
>
077.
<
genre
>Romance</
genre
>
078.
<
price
>4.95</
price
>
079.
<
publish_date
>2000-11-02</
publish_date
>
080.
<
description
>
081.
A deep sea diver finds true love twenty
082.
thousand leagues beneath the sea.
083.
</
description
>
084.
</
book
>
085.
<
book
id
=
"bk108"
>
086.
<
author
>Knorr, Stefan</
author
>
087.
<
title
>Creepy Crawlies</
title
>
088.
<
genre
>Horror</
genre
>
089.
<
price
>4.95</
price
>
090.
<
publish_date
>2000-12-06</
publish_date
>
091.
<
description
>
092.
An anthology of horror stories about roaches,
093.
centipedes, scorpions and other insects.
094.
</
description
>
095.
</
book
>
096.
<
book
id
=
"bk109"
>
097.
<
author
>Kress, Peter</
author
>
098.
<
title
>Paradox Lost</
title
>
099.
<
genre
>Science Fiction</
genre
>
100.
<
price
>6.95</
price
>
101.
<
publish_date
>2000-11-02</
publish_date
>
102.
<
description
>
103.
After an inadvertant trip through a Heisenberg
104.
Uncertainty Device, James Salway discovers the problems
105.
of being quantum.
106.
</
description
>
107.
</
book
>
108.
<
book
id
=
"bk110"
>
109.
<
author
>O'Brien, Tim</
author
>
110.
<
title
>Microsoft .NET: The Programming Bible</
title
>
111.
<
genre
>Computer</
genre
>
112.
<
price
>36.95</
price
>
113.
<
publish_date
>2000-12-09</
publish_date
>
114.
<
description
>
115.
Microsoft's .NET initiative is explored in
116.
detail in this deep programmer's reference.
117.
</
description
>
118.
</
book
>
119.
<
book
id
=
"bk111"
>
120.
<
author
>O'Brien, Tim</
author
>
121.
<
title
>MSXML3: A Comprehensive Guide</
title
>
122.
<
genre
>Computer</
genre
>
123.
<
price
>36.95</
price
>
124.
<
publish_date
>2000-12-01</
publish_date
>
125.
<
description
>
126.
The Microsoft MSXML3 parser is covered in
127.
detail, with attention to XML DOM interfaces, XSLT processing,
128.
SAX and more.
129.
</
description
>
130.
</
book
>
131.
<
book
id
=
"bk112"
>
132.
<
author
>Galos, Mike</
author
>
133.
<
title
>Visual Studio 7: A Comprehensive Guide</
title
>
134.
<
genre
>Computer</
genre
>
135.
<
price
>49.95</
price
>
136.
<
publish_date
>2001-04-16</
publish_date
>
137.
<
description
>
138.
Microsoft Visual Studio 7 is explored in depth,
139.
looking at how Visual Basic, Visual C++, C#, and ASP+ are
140.
integrated into a comprehensive development
141.
environment.
142.
</
description
>
143.
</
book
>
144.
</
catalog
>