Using Jdom to read XML configuration files in Java

Source: Internet
Author: User
Tags xpath
There is a Web project that has a configuration file under the SRC directory webconfig.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<services> <service name= "Apnserver" url= "http://"
	192.168.1.89:7070/"/>
</services>

Handwritten XML parsing class, provided that you add Jdom-2.0.5.jar, Jaxen-1.1.1.jar two jar packages to your project
Import java.io.IOException;

Import java.util.List;
Import org.jdom2.Document;
Import org.jdom2.Element;
Import org.jdom2.JDOMException;
Import Org.jdom2.input.SAXBuilder;

Import Org.jdom2.xpath.XPath; public class Xmlparse {//resolves the corresponding URL from the document public static string GetContent (String attributename) {Saxbuilder sax = new sax 
		 Builder ();
		Document Doc;
			try {doc = Sax.build (XMLParse.class.getResource ("/"). GetPath () + "Webconfig.xml");  
	         
	        Element Rootele = Doc.getrootelement (); 
	        List servicelist = Xpath.selectnodes (Rootele, "//services/service"); if (Servicelist!=null&&servicelist.size () >0) {for (int i = 0; i < servicelist.size (); i++) {E
					Lement service= (Element) servicelist.get (i); if (Attributename!=null&&attributename.equals (Service.getattributevalue ("name")) {return
					Service.getattributevalue ("url");
	        }}else{return null; The catch (Jdomexception e) {e). Printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
	return null; }
}

Can be invoked in other classes

public class Getpostutil {
	public  static String Androidpushnotificationurl = "";
	static{
		androidpushnotificationurl=xmlparse.getcontent ("Apnserver");
	}

Related Article

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.