package schedulers;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import util.PubFun;
public class XMLReader {
private Document instance = null;
public XMLReader( File file ) {
try {
final SAXReader xmlReader = new SAXReader();
instance = xmlReader.read(file);
} catch (DocumentException e) {
System.out.println(file.getPath() + " can't be found");
}
}
public XMLReader(StringReader stringReader) {
try {
final SAXReader xmlReader = new SAXReader();
instance = xmlReader.read(stringReader);
//logger.debug("StringReader successfully loaded");
} catch (DocumentException e) {
System.out.println("StringReader can't be load => "+stringReader.toString());
}
}
public XMLReader(String strXML) {
try {
instance = DocumentHelper.parseText(strXML);
} catch (DocumentException e) {
System.out.println("StringReader can't be load => "+strXML);
}
}
public String getValue( String nodeName ) {
if (!PubFun.isNullorBlank(nodeName)) {
final Node node = instance.selectSingleNode(nodeName);
return ("null".equals(node.getText()) ? null : node.getText());
} else {
System.out.println("String is NULL");
return null;
}
}
public List getNodes( String nodeName ) {
if (!PubFun.isNullorBlank(nodeName)) {
List listNodes = instance.selectNodes(nodeName);
return listNodes;
} else {
System.out.println("String is NULL");
return null;
}
}
public String getNodeValue( Node node, String nodeName ) {
if (!PubFun.isNullorBlank(nodeName)) {
final Node subNode = node.selectSingleNode(nodeName);
return ("null".equals(subNode.getText()) ? null : subNode.getText());
} else {
System.out.println("String is NULL");
return null;
}
}
public boolean removeNode(Node node){
return node.getParent().remove(node);
}
public Element addElement(String elementName){
return instance.getRootElement().addElement(elementName);
}
public Document getRoot(){
return instance;
}
public String writeToString(){
StringWriter strReturn = new StringWriter();
XMLWriter writer = null;
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
try {
//writer= new XMLWriter(ll,format);
writer = new XMLWriter(strReturn,format);
//writer = new XMLWriter(new FileOutputStream(new File("c:\\aaa.xml")),format);
writer.write(instance);
writer.close();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return strReturn.toString();
}
}