import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
public class XmlUtil {
private String xmlpath = "";
private Document doc = null;
private String contentnode = "//result";
public XmlUtil() {
//
}
public XmlUtil(String xmlpath) {
this.xmlpath = xmlpath;
initial();
}
private void initial() {
SAXBuilder reader = new SAXBuilder();
try {
doc = reader.build(new File(xmlpath));
} catch (JDOMException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public Element getRootElement() {
if (doc == null)
return null;
return doc.getRootElement();
}
public void AddElement(Element parEle, Element childEle) {
parEle.addContent(childEle);
}
public void writeDoc() {
XMLOutputter out = new XMLOutputter();
Format f = Format.getPrettyFormat();
f.setEncoding("UTF-8");
out.setFormat(f);
out.getFormat().setEncoding("UTF-8");
try {
FileWriter xmlWrite = new FileWriter(xmlpath);
out.output(doc, xmlWrite);
xmlWrite.flush();
xmlWrite.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
public List getXmlEleList() {
XPath path = null;
try {
path = XPath.newInstance(contentnode);
} catch (JDOMException e1) {
System.out.println(e1.getMessage());
}
List list = null;
try {
list = path.selectNodes(doc);
} catch (JDOMException e1) {
System.out.println(e1.getMessage());
}
return list;
}
@SuppressWarnings("rawtypes")
public List getXmlEleList(String xpathtype) {
XPath path = null;
try {
path = XPath.newInstance(xpathtype);
} catch (JDOMException e1) {
System.out.println(e1.getMessage());
}
List list = null;
try {
list = path.selectNodes(doc);
} catch (JDOMException e1) {
System.out.println(e1.getMessage());
}
return list;
}
/** 当前节点向上找指定名称的父节点 **/
public Element findInParEle(Element nowNode, String nodename) {
Element parEle = nowNode.getParentElement();
if (parEle == null)
return null;
if (parEle.getName().equals(nodename))
return parEle;
else
return findInParEle(parEle, nodename);
}
public void createXmlFile(String filepath, String root_name) {
// 生成解析结果的模板文档
Element rootNode = new Element(root_name);
Document parsersultdoc = new Document(rootNode);
XMLOutputter fmt = new XMLOutputter();
try {
// 生成解析模板文档
FileWriter writer = new FileWriter(filepath);
Format f = Format.getPrettyFormat();
f.setEncoding("UTF-8");
fmt.setFormat(f);
fmt.output(parsersultdoc, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XmlUtil xu = new XmlUtil();
xu.createXmlFile("C:/a.xml", "testroot");
}
}