Java XML reading (using Dom + XPath)

Source: Internet
Author: User

The following math. xml file is used as the example XML file. The document shows the math score of an exam, which contains the score of student LZX and ZJ.

 

------------- Math. xml -------------

<Math>

<Student ID = "1">

<Name> ZJ </Name>

<Score> 87 </score>

</Student>

<Student ID = "2">

<Name> LZX </Name>

<Score> 85 </score>

</Student>

</Math>

-------------------------------------

Perform the following operations:

 

1. Read math. XML to memory

Documentbuilderfactory DBF = documentbuilderfactory.Newinstance();

Documentbuilder DB = DBF. newdocumentbuilder ();

File F =NewFile ("D:" "math. xml ");

Document Doc = dB. parse (f );

 

2. Obtain the student node list

Xpathfactory = xpathfactory.Newinstance();

XPath = xpathfactory. newxpath ();

Nodelist list = (nodelist) XPath. Evaluate ("Math/student", doc,

Xpathconstants.Nodeset);

 

3. Obtain the first node with student as the node.

Xpathfactory = xpathfactory.Newinstance();

XPath = xpathfactory. newxpath ();

Node node = (node) XPath. Evaluate ("Math/student", doc,

Xpathconstants.Node);

 

Complex functions can be implemented based on the DOM tree structure and XPath path.

XPath Syntax: http://www.w3school.com.cn/xpath/xpath_syntax.asp

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.