search
HomeBackend DevelopmentXML/RSS TutorialA detailed introduction to teach you how to quickly find information from an XML file

In the Internet era, xml files play a role in saving and transmitting data. The Soap protocol communicates information through Xml, and the database is accessed through Xml files, etc. So how to quickly obtain the required information from an XML file?

We know that both Java's JAXP and Microsoft.Net have Xml parsers. Microsoft.Net analyzes while reading, while JAXP reads it into the memory and then analyzes it (there is also an event mechanism to read), in short, is not conducive to fast reading. Based on this, both Microsoft.Net and JAXP provide the XPATH mechanism to quickly locate the required nodes in the XML file.

For example, there is an XML file: booksort.xml:

<?xml version="1.0"?>

<!-- a fragment of a book store inventory database -->

<bookstore xmlns: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&#39;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>

If we want to quickly find all title names with "last-name" equal to "Austen", we can get it through the following method:

XmlReaderSample.cs

//Corelib.net/System.Xml.Xsl/XPathDocument Class

//Author :Any 


using System;

using System.IO;

using System.Xml;

using System.Xml.XPath;


public class XmlReaderSample

{

public static void Main()

{

XmlTextReader myxtreader = new XmlTextReader("booksort.xml");

XmlReader myxreader = myxtreader;

XPathDocument doc = new XPathDocument(myxreader);

XPathNavigator nav = doc.CreateNavigator();


XPathExpression expr; 

expr = nav.Compile("descendant::book[author/last-name=&#39;Austen&#39;]");


//expr.AddSort("title", XmlSortOrder.Ascending, XmlCaSEOrder.None, "", XmlDataType.Text);


XPathNodeIterator iterator = nav.Select(expr);

while (iterator.MoveNext())

{

XPathNavigator nav2 = iterator.Current;

nav2.MoveToFirstChild();

Console.WriteLine("Book title: {0}", nav2.Value);

}

}

}

Run this program, the result is:

Book title: Pride And Prejudice

Book title: Emma

Book title: Sense and Sensibility

You can see that the search is correct.

Using some functions in XPATH, simple sorting and simple operations can also be achieved. If you often need to summarize data in a database, you can use XPATH to achieve this.

For example:

order.xml

<!--Represents a customer order-->

<order>

<book ISBN=&#39;10-861003-324&#39;>

<title>The Handmaid&#39;s Tale</title>

<price>19.95</price>

</book>

<cd ISBN=&#39;2-3631-4&#39;>

<title>Americana</title>

<price>16.95</price>

</cd>

</order>

and: books.xml

<?xml version="1.0"?>

<!-- This file represents a fragment of a book store inventory database -->

<bookstore>

<book cc="dd" xmlns:bk="urn:sample" xmlns:ns="http://www.Any.com" genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">

<title>The Autobiography of Benjamin Franklin</title>

<ns:author>

<first-name>Benjamin</first-name>

<last-name>Franklin</last-name>

</ns:author>

<price>8.99</price>

</book>

<book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">

<title>The Confidence Man</title>

<author>

<first-name>Herman</first-name>

<last-name>Melville</last-name>

</author>

<price>11.99</price>

</book>

<book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">

<title>The Gorgias</title>

<author>

<name>Plato</name>

</author>

<price>9.99</price>

</book>

</bookstore>

We can sum the prices in the XML file to get the total price.

Evaluate.cs

//Corelib.net/System.Xml.Xsl/XPathNavigator Class

//Author :Any 


using System;

using System.IO;

using System.Xml;

using System.Xml.XPath;



public class EvaluateSample

{

public static void Main()

{

EvaluateSample myEvaluateSample = new EvaluateSample();

myEvaluateSample.test("books.xml");

}


public void test(String args)

{

try

{

//test Evaluate(String);

XPathDocument myXPathDocument = new XPathDocument(args);

XPathNavigator myXPathNavigator = myXPathDocument.CreateNavigator();

Console.WriteLine(myXPathNavigator.Evaluate("sum(descendant::book/price)"));


//testEvaluate(XPathExpression);

XmlDocument doc = new XmlDocument();

doc.Load("order.xml");

XPathNavigator nav = doc.CreateNavigator();

XPathExpression expr = nav.Compile("sum(//price/text())");

Console.WriteLine(nav.Evaluate(expr));


//testEvaluate(XPathExpression);


XPathNodeIterator myXPathNodeIterator = nav.Select("descendant::book/title");

expr = nav.Compile("sum(//price/text())");

Console.WriteLine(nav.Evaluate(expr,myXPathNodeIterator));


} 

catch (Exception e)

{

Console.WriteLine ("Exception: {0}", e.ToString());

}

}


}

Run this program, the results are as follows:

30.97

36.9

36.9

We can see that 30.97 is the sum of all price values ​​​​in books.xml, and 36.9 is the sum of all price values ​​​​in order.xml sum. Not only can you quickly find information through XPAH, but you can also perform some basic processing on the information.

The above is a detailed introduction to teach you how to quickly find information from an XML file. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Building Feeds with XML: A Hands-On Guide to RSSBuilding Feeds with XML: A Hands-On Guide to RSSApr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

XML's Role in RSS: The Foundation of Syndicated ContentXML's Role in RSS: The Foundation of Syndicated ContentApr 12, 2025 am 12:17 AM

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor