在网络时代,xml(标准化越来越近了)文件起到了一个保存和传输数据的作用。Soap协议通过xml(标准化越来越近了)交流信息,数据库通过xml(标准化越来越近了)文件存取等等。那么怎样快速的从一个xml(标准化越来越近了)文件中取得所需的信息呢?
我们知道,JAVA的JAXP中和Microsoft.Net都有xml(标准化越来越近了)分析器,Microsoft.Net是边读边分析,而JAXP是读到内存中然后才进行分析(还有一种是事件机制去读),总而言之,是不利于快速读取。基于此,Microsoft.Net 和JAXP都提供了XPATH机制,来快速定位到xml(标准化越来越近了)文件中所需的节点。
例如有一个xml(标准化越来越近了)文件:booksort.xml(标准化越来越近了):
<?xml(标准化越来越近了) version="1.0"?>
<!-- a fragment of a book store inventory database -->
<bookstore xml(标准化越来越近了)ns:bk="urn:samples">
<book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
<title>Pride And Prejudice</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>24.95</price>
</book>
<book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>29.95</price>
</book>
<book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
<title>Emma</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
<book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
<title>Sense and Sensibility</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
</bookstore>
如果我们想快速查找”last-name”等于”Austen”的所有标题名,可以通过以下方法可以得到:
xml(标准化越来越近了)ReaderSample.cs
//Corelib.net/System.xml(标准化越来越近了).Xsl/XPathDocument Class
//Author :Any
using System;
using System.IO;
using System.xml(标准化越来越近了);
using System.xml(标准化越来越近了).XPath;
public class xml(标准化越来越近了)ReaderSample
{
public static void Main()
{
xml(标准化越来越近了)TextReader myxtreader = new xml(标准化越来越近了)TextReader("booksort.xml(标准化越来越近了)");
xml(标准化越来越近了)Reader myxreader = myxtreader;
XPathDocument doc = new XPathDocument(myxreader);
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr;
expr = nav.Compile("descendant::book[author/last-name='Austen']");
//expr.AddSort("title", xml(标准化越来越近了)SortOrder.Ascending, xml(标准化越来越近了)CaseOrder.None, "", xml(标准化越来越近了)DataType.Text);
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext())
{
XPathNavigator nav2 = iterator.Current;
nav2.MoveToFirstChild();
Console.WriteLine("Book title: {0}", nav2.Value);
}
}
}
运行这个程序,结果为:
Book title: Pride And Prejudice
Book title: Emma
Book title: Sense and Sensibility
可以看到查找正确。
利用XPATH中的一些功能,也可以实现简单的排序和简单运算。如在数据库中经常要对数据进行汇总,就可用XPATH实现。
如:
order.xml(标准化越来越近了)
<!--Represents a customer order-->
<order>
<book ISBN='10-861003-324'>
<title>The Handmaid's Tale</title>
<price>19.95</price>
</book>
<cd ISBN='2-3631-4'>
<title>Americana</title>
<price>16.95</price>
</cd>
</order>
和:books.xml(标准化越来越近了)
<?xml(标准化越来越近了) version="1.0"?>
<!-- This file represents a fragment of a book store inventory database -->