I. Overview-How to parse an XML file
As the environmental information of the project needs to change frequently, it needs to be configured as a global variable, can use an XML file to save the global information, then parse the XML file, pass the information to the function API, then how to parse this XML document, see below, tks!
Two. Writing tool classes for parsing XML parsexml
public class Parsexml {
Private log log = new log (This.getclass ());
/**
* Parse XML file, we need to know the path of the XML file, and then load the XML file according to its path, generate a Document object,
* So we first define two variables string filepath,document Document
* Then define a load method, which is used to load the XML file, resulting in the Document object.
*/
Private String FilePath;
Private document document;
/**
* When the constructor is used for the new Parsexml object, a filepath parameter is passed in to initialize the FilePath value
* Call the Load method so that when the Parsexml object is generated, a document object is generated.
*/
Public Parsexml (String FilePath) {
This.filepath = FilePath;
This.load (This.filepath);
}
/**
* Used to load an XML file and produce an object of document
*/
private void Load (String filePath) {
File File = new file (FilePath);
if (file.exists ()) {
Saxreader Saxreader = new Saxreader ();
try {
Document = Saxreader.read (file);
} catch (Documentexception e) {
Log.info ("File load exception:" + FilePath);
throw new Definedexception ("File load exception:" + FilePath);
}
} else{
Log.info ("File does not exist:" + FilePath);
throw new Definedexception ("file does not exist:" + FilePath);
}
}
Three. Write a class to load the global configuration XML file and convert it to static data for the function API to get directly
Public classConfig {Private StaticLog log=NewLog (Config.class); Public StaticString Browser; Public Static intWaitTime; Static{parsexml px=NewParsexml ("Config/config.xml"); Browser=px.getelementtext ("/config/browser"); Log.info ("The browser is:" +browser); WaitTime=integer.valueof (Px.getelementtext ("/config/waittime")); Log.info ("The Wait Time is:" +waitTime); }}
}
How to parse an XML file