Use JDOM's XPath to quickly locate XML nodes

Source: Internet
Author: User



Use JDOM's XPath to quickly locate XML nodes
Original jaie (Participation score: 291, expert score: 1420) published: Version: 1.0 read:3162Times

Key words: XPath, JDOM

When using JDOM to parse XML documents, we often need to quickly locate a node for reading or modifying operations. Locate the node. This is where the XPath expression works. Since Beta 9 (downloaded from www.jdom.org), JDOM supports parsing XPath path expressions, which makes it much easier for us to use JDOM to parse XML documents. See the example

1. The example uses an XML file, KK. xml

<? XML version = "1.0" encoding = "gb2312"?>
<Contact list>
<Contact>
<Name> Zhang San </Name>
<ID> 001 </ID>
<Company> Company A </company>
<Email> zhang@aaa.com </Email>
<Phone number type = "company"> (010) 62345678 </phone number>
<Phone number type = "family"> (010) 88888888 </phone number>
<Address>
<Street> No. 1234 Fifth Street </street>
<City> Beijing </city>
<Province> Beijing </province>
</Address>
</Contact>


Li Si
002
Company B
li@bbb.org
(021) 87654321


No. 9876 Nanjing Road
Shanghai
Shanghai

2. To find the phone number of Michael Jacob's family, use the followingCodeSegment

Package test;

Import java. util. List;
Import java.net. url;
Import org. JDOM .*;
Import org. JDOM. XPath .*;
Import org. JDOM. Input .*;
Import java. Io .*;
Import java. util .*;

Public class test {
Public static void main (string [] ARGs) throws exception {

Saxbuilder builder = new saxbuilder ();
Document Doc = builder. Build ("KK. xml ");
Element root = Doc. getrootelement ();

XPath = XPath. newinstance ("// phone number [../name = 'zhang san'] [@ type = 'home']");
List list = XPath. selectnodes (Root );

Iterator iter = List. iterator ();
While (ITER. hasnext ()){
Element item = (element) ITER. Next ();
System. Err. println (item. gettext ());
}

}

The output result is exactly what we want: (010) 88888888. How about it, very convenient :).

After 8, my expression is not necessarily the most efficient. You have better understanding of xpath and better query efficiency.

Hope this little articleArticleI am inspired by you. If you have any mistakes, please criticize and correct them.

Copyright Notice to the author
Does this article help you? Vote: Yes NoVoting Result: 6 1


Reviewer:YangwqParticipation score: 6 Expert score: 0 Posting time:
How can I modify the phone number of Michael Jacob's family ??

I found the JDOM 9 beta package on the web and referenced JDOM. jar, xerces. jar, jaxen-core.jar, jaxen-jdom.jar, saxpath. jar in jbuild 7, which allows XPath to quickly locate XML nodes.
But there is no example of modifying the node value?

I found the setvariable method in the XPath class in the doc.

The following code snippet is used to change the "Phone Number of Michael Jacob's family" to "Modify the phone number of Michael Jacob's family:

Import java. util. List;
Import java.net. url;
Import org. JDOM .*;
Import org. JDOM. XPath .*;
Import org. JDOM. Input .*;
Import java. Io .*;
Import java. util .*;

Public class test {
Public static void main (string [] ARGs) throws exception {

saxbuilder builder = new saxbuilder ();
document DOC = builder. build ("cc. XML ");
element root = Doc. getrootelement ();
// find the phone number of Michael Jacob's family.
XPath = XPath. newinstance ("// call [.. /name = 'zhang san'] [@ type = 'home'] ");

List list = XPath. selectnodes (Root );
XPath. setvariable ("household", "12312313 ");

/*
Iterator iter = List. iterator ();
While (ITER. hasnext ()){
Element item = (element) ITER. Next ();
System. Err. println (item. gettext ());
}
*/
}
}

This Code cannot be used to "Modify Michael's home phone number". How can I modify it?

COMMENTATOR: jaie score: 291 expert score: 1420 from: Beijing published on:
the setvariable method of xpath is used to set the form parameters in the XPath expression. It is not used to change nodes. You need to change nodes, use the Set Method of element.

iterator iter = List. iterator ();
while (ITER. hasnext () {
element item = (element) ITER. next ();
item. settext ("aaaaaaaaaaaaaaaaaaa");
}

if you want to save the changes made to the XML document, please refer to the code!

xmloutputter outputter = new xmloutputter ();
outputter. settexttrim (true);
outputter. setindent ("");
outputter. setnewlines (true);
outputter. setencoding ("gb2312");

string S = outputter. output (Doc, new fileoutputstream ("AAA. XML ");

Reviewer:Djb_skyfaceScore: 36 expert score: 0 Posting time:
I tried the landlord's method and found a problem, which is the one before the name ".. "Cause, I will .. change to //. I don't know if it is the new version (jdom10beta ).
There are two different approaches:
1. My Approach
Saxbuilder builder = new saxbuilder ();
Document Doc = builder. Build ("Tel. xml ");
Element root = Doc. getrootelement ();
XPath = XPath. newinstance ("// phone number [// name = 'zhang san'] [@ type = 'home']");
Element E = (element) XPath. selectsinglenode (Root );
// XPath. setvariable ("// call [// name = 'zhang san'] [@ type = 'home']", "33333333 ");
System. Out. println (E. gettext ());
2. Path of the landlord
Saxbuilder builder = new saxbuilder ();
Document Doc = builder. Build ("Tel. xml ");
Element root = Doc. getrootelement ();
XPath = XPath. newinstance ("// phone number [// name = 'zhang san'] [@ type = 'home']");
List list = XPath. selectnodes (Root );
Iterator iter = List. iterator ();
While (ITER. hasnext ()){
Element item = (element) ITER. Next ();
System. Err. println (item. gettext ());
}
Both methods are acceptable, but I think my approach is more natural to understand, because a node does not need to be traversed.

In addition, I tried the element. settext () method provided by the landlord. I cannot modify the XML file.Source code

Saxbuilder builder = new saxbuilder ();
Document Doc = builder. Build ("Tel. xml ");
Element root = Doc. getrootelement ();
XPath = XPath. newinstance ("// phone number [// name = 'zhang san'] [@ type = 'home']");
List list = XPath. selectnodes (Root );
Iterator iter = List. iterator ();
While (ITER. hasnext ()){
Element item = (element) ITER. Next ();
Item. settext ("333333333 ");
System. Err. println (item. gettext ());
}
This code can only modify the printed result and cannot modify the values in the XML file.

comments: djb_skyface score: 36 expert score: 0 published on:
Forgive me for my negligence.
However, the landlord's Code seems to be more concise:

Landlord code:

Xmloutputter outputter = new xmloutputter ();
Outputter. settexttrim (true );
Outputter. setindent ("");
Outputter. setnewlines (true );
Outputter. setencoding ("gb2312 ");
String S = outputter. Output (Doc, new fileoutputstream ("AAA. xml "));

My code:

String indent = ""; // if the preceding KK. xml file is modified, no more indent is required.
Boolean newlines = true; // no new line is required
Xmloutputter outp = new xmloutputter (indent, newlines, "gb2312 ");
Outp. settexttrim (true );
Outp. Output (Doc, new fileoutputstream ("AAA. xml "));

Generate Doc

Guest: eastasp Posting time:
For example, in the XML below, I cannot even get the number of attribute attributes in the row.
<? XML version = "1.0" standalone = "yes"?>
-<! -- Edited with xmlspy V5 Rel. 3 U (http://www.xmlspy.com) by heavyz (Nanjing University)
-->
-<Datapacket version = "2.0">
-<Metadata>
-<Fields>
<Field attrname = "bsmt_materialid" fieldtype = "string" width = "20"/>
<Field attrname = "bsmt_barcode" fieldtype = "string" width = "30"/>
<Field attrname = "bsmt_name" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_specification" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_model" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_color" fieldtype = "string" width = "30"/>
<Field attrname = "bsmt_unitweight" fieldtype = "R8" width = "22"/>
<Field attrname = "bsmt_unitname" fieldtype = "string" width = "5"/>
<Field attrname = "bsmt_depotid" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_providerid" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_type" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_sort" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_note" fieldtype = "string" width = "200"/>
<Field attrname = "bsmt_reserve1" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_reserve2" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_reserve3" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_reserve4" fieldtype = "string" width = "50"/>
<Field attrname = "bsmt_reserve5" fieldtype = "string" width = "50"/>
</Fields>
<Params/>
</Metadata>
-<Rowdata>
<Row bsmt_materialid = "0002" bsmt_barcode = "0000000002"/>
<Row bsmt_materialid = "001"/>
<Row bsmt_materialid = "0015" bsmt_barcode = "0020"/>
<Row bsmt_materialid = "0016" bsmt_barcode = "0020"/>
<Row bsmt_materialid = ">" bsmt_barcode = "0020"/>
<Row bsmt_materialid = "0018" bsmt_barcode = "0020"/>
<Row bsmt_materialid = "0019" bsmt_barcode = "0020"/>
<Row bsmt_materialid = "002"/>
<Row bsmt_materialid = "0020" bsmt_barcode = "0020"/>
<Row bsmt_materialid = "002001" bsmt_barcode = "0000000"/>
<Row bsmt_materialid = "003"/>
<Row bsmt_materialid = "004"/>
<Row bsmt_materialid = "005"/>
<Row/>
<Row/>
</Rowdata>
</Datapacket>

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.