/*
* @(#)XMLFileUtil.java 1.0 2004/12/20
*
* Copyright 2004 Shark Wang, All rights reserved.
*/
packagenet.csdn.blog.xport;importjava.net.URL;importjava.util.Iterator;importorg.apache.log4j.LogManager;importorg.apache.log4j.Logger;importorg.dom4j.Attribute;importorg.dom4j.Document;importorg.dom4j.Element;importorg.dom4j.io.SAXReader;/**
* The XmlUtil
class supported your code to read/write xml
* data from the file. all methods in this class depend on dom4j
.
*
*@authorShark Wang
*@version1.0, 2004/12/20
*@sinceTutorial 1.0
*/publicclassXMLFileUtil {privatestaticLogger logger = LogManager.getLogger(XMLFileUtil.class);/**
* read xml content from some file, and load xml data into the
* Document object.
*
*@paramfilePath String
*@returnDocument
*/publicstaticDocument LoadXmlFile(String filePath) {/* marked by Shark Wang
*****************************************************************
//get resolver to ignore the DTD validation
EntityResolver resolver = new EntityResolver() {
public InputSource resolveEntity(String publicId,
String systemId) {
return new InputSource(new StringBufferInputStream(""));
}
};
//create reader
SAXReader reader = new SAXReader();
//set reader attribute to ignore DTD validation
reader.setEntityResolver(resolver);
reader.setValidation(false);
reader.setIncludeExternalDTDDeclarations(false);
reader.setIncludeInternalDTDDeclarations(false);
*******************************************************************
*/SAXReader reader =newSAXReader();//try to load xml data into Document objectDocument doc =null;try{
String urlString =null;if(filePath.startsWith("/")) {
urlString = "file://" + filePath;
}else{
urlString = "file:///" + filePath;
}
logger.debug("XML File's URL :" + urlString);
doc = reader.read(newURL(urlString));
}catch(Exception ex) {
logger.info("Can not load " + filePath);
logger.debug(ex.getMessage(), ex);
}//return Document objectreturndoc;
}/**
* Get attribute value by name for some xml element.
*
*@paramelement Element
*@paramattributeName String
*@returnString
*/publicstaticString getAttributeValue(Element element,
String attributeName) {
String attributeValue =null;for(Iterator i = element.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();if(attribute.getName().equals(attributeName)) {
attributeValue = (String) attribute.getData();break;
}
}returnattributeValue;
}publicstaticElement findElement(Element searchedElement,
String targetNodePrefix,
String targetNodeAttributeName,
String targetNodeAttributeValue) {
Element elementTarget =null;for(Iterator i = searchedElement.elementIterator(targetNodePrefix);
i.hasNext(); ) {
Element element = (Element) i.next();
String strManagerName =
XMLFileUtil.getAttributeValue(element,
targetNodeAttributeName);if(strManagerName.equals(targetNodeAttributeValue)) {
elementTarget = element;break;
}
}returnelementTarget;
}privateXMLFileUtil() {
}
}