Parsing XML files with XPath

Source: Internet
Author: User
Tags xpath

Parsing XML files with XPath

One, XPath

XPath is a language that looks up information in an XML document and can be used to traverse elements and attributes in an XML document.

XPath expressions are much easier to write than cumbersome Document Object Model (DOM) code. The quickest and easiest way to extract information from an XML document is to embed an XPath expression in a Java program. The Javax.xml.xpath package is introduced in the Java version, a library that is independent of the XML object model for XPath document queries.

Two, XPath API

1.XPathFactory class
The Xpathfactory instance can be used to create an XPath object. The class has only a protected, empty construction method, and the common method is:
Static Xpathfactory newinstance (): Gets a new xpathfactory instance that uses the default object model (DOM).

2. XPath interface

Provides access to an XPath computing environment and expressions. XPath objects are not thread-safe and cannot be loaded repeatedly. This means that the application is responsible for ensuring that multiple threads cannot use an XPath object at any given time.
Common methods:
XPathExpression compile (String expression): Compiles an XPath expression.

3 Xpath.evaluate ()

1) xpath.evaluate (String expression, InputSource source, QName ReturnType): Evaluates an XPath expression in the specified InputSource context and returns the result of the specified type.

2) xpath.evaluate (String expression, Object item, QName returntype): Evaluates an XPath expression in the specified context and returns the result of the specified type.

The third parameter is the return type that you want to specify, and the value of the parameter is a static field that has been named in Xpathconstants. As follows:
Xpathconstants.boolean
Xpathconstants.nodeset
Xpathconstants.number
Xpathconstants.string
Xpathconstants.string

Xpathconstants.node

Note: Xpathconstants.node It mainly applies when XPath expressions have the result and only one node. If an XPath expression returns more than one node, but the specified type is Xpathconstants.node, the Evaluate () method returns the first node in document order. If the result of an XPath expression is an empty set, but the specified type is Xpathconstants.node, the Evaluate () method returns NULL.

Three, Java code implementation

1.xml file

<location>
  <property>
     <name>city</name>
     <value>beijing</value>
  </property>
  <property>
      <name>district</name>
      <value>chaoyang </value>
  </property>
</location>

2. Parse the XML file above

Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import Javax.xml.xpath.XPath;
Import javax.xml.xpath.XPathConstants;

Import Javax.xml.xpath.XPathFactory;
Import org.w3c.dom.Document;
Import Org.w3c.dom.Node;

Import org.w3c.dom.NodeList; public class Xpathtest {public static void main (String args[]) {try {//Parse document Documentbuilderfactory DOMF
			  Actory = Documentbuilderfactory.newinstance (); Domfactory.setnamespaceaware (TRUE);
			  Never forget this!
			  Documentbuilder builder = Domfactory.newdocumentbuilder ();
			  
			   Document doc = Builder.parse ("City.xml"); Xpathfactory factory = Xpathfactory.newinstance (); Create xpathfactory XPath XPath = Factory.newxpath ()///Create XPath object with this factory nodelist nodes = (nodelist) XPATH.E
			   Valuate ("Location/property", Doc, Xpathconstants.nodeset);
			   String name = "";
			   String value = ""; for (int i = 0; i < nodes.getlength (); i++) {node node = nodes.iTEM (i);
			        Name = (String) xpath.evaluate ("Name", node, xpathconstants.string);
			        Value = (String) xpath.evaluate ("Value", node, xpathconstants.string);
			   System.out.println ("name=" +name+ "; value=" +value);
		The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
 }
	}

}

Run Result:

Name=city;value=beijing
Name=district;value=chaoyang

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.