最近闲着没事,简单整理一下java读写xml的方法,以前也就是匆匆忙忙的使用,没有认真的思考过,本人菜鸟,希望各位老鸟指正!
本来想总结一下常用的读写xml的四个方法,为了写程序方便,定义了接口,事与愿违,有时间以后补上吧!
定义接口如下:
[b]1[/b].Dom读写xml方法
[b]2.[/b] dom4j 读写xml以及xpath的简单使用。
说明:Dom4j用到了 dom4j-1.6.1.jar 和 jaxen-1.1-beta-6.jar 都能在下载的dom4j包中找到。
本来想总结一下常用的读写xml的四个方法,为了写程序方便,定义了接口,事与愿违,有时间以后补上吧!
定义接口如下:
public interface ParserXmlInterface
{
//创建xml
public void createXml(String path);
//解析xml
public void parserXml(String fileName);
//为dom4j xpath定义
public void xpathDom4j(String path);
}
[b]1[/b].Dom读写xml方法
public class DomParaserXmlImpl
implements ParserXmlInterface
{
private Document document;
// 实现接口生成xml方法
public void createXml(String path)
{
// 初始化DOM
this.initDocument();
// 创建元素,并添加节点
Element root = this.document.createElement("employess");
this.document.appendChild(root);
Element employee = this.document.createElement("employee");
Element name = this.document.createElement("name");
name.appendChild(this.document.createTextNode("gshzhou"));
employee.appendChild(name);
Element sex = this.document.createElement("sex");
sex.appendChild(this.document.createTextNode("male"));
employee.appendChild(sex);
Element age = this.document.createElement("age");
age.appendChild(this.document.createTextNode("25"));
employee.appendChild(age);
root.appendChild(employee);
try
{
// 确定要创建的哪一个 Factory 实现被命名为
TransformerFactory transFactory = TransformerFactory.newInstance();
// 将原树转换为结果树。可以在转换之间保留参数和输出属性
Transformer tf = transFactory.newTransformer();
// 创建带有DOM节点的新输入源
DOMSource domSource = new DOMSource(document);
// 设置转换中实际的输出属性。
tf.setOutputProperty(OutputKeys.INDENT, "yes");
// java.io 向文本输出流打印对象的格式化表示形式。
PrintWriter writer = new PrintWriter(new FileOutputStream(path));
// 从字节流构造充当结果的持有者
StreamResult result = new StreamResult(writer);
// 讲xml转换为目标结果。
tf.transform(domSource, result);
System.out.println("xml生成成功");
}
catch (Exception e)
{
System.out.println("生成xml时异常:" + e.getMessage());
}
}
// 实现接口解析xml
public void parserXml(String fileName)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = factory.newDocumentBuilder();
document = db.parse(fileName);
NodeList employees = document.getChildNodes();
for( int i = 0; i < employees.getLength(); i++)
{
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for( int j = 0; j < employeeInfo.getLength(); j++)
{
Node node = employeeInfo.item(j);
NodeList employeeMate = node.getChildNodes();
for( int k = 0; k < employeeMate.getLength(); k++)
{
System.out.println(employeeMate.item(k).getNodeName()
+ ":" + employeeMate.item(k).getTextContent());
}
}
}
System.out.println("DOM 解析完毕");
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("解析xml异常:" + e.getMessage());
}
}
// 初始化dom
private void initDocument()
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.document = builder.newDocument();
}
catch (ParserConfigurationException e)
{
System.out.println("初始化DOM异常>");
}
}
//方法是为Dom4j定义的接口,用xpath很方便 的找到节点的属性以及值。
public void xpathDom4j(String path)
{
}
}
[b]2.[/b] dom4j 读写xml以及xpath的简单使用。
public class Dom4jParaserXmlImpl
implements ParserXmlInterface
{
//dom4j生成xml
public void createXml(String path)
{
Document document = DocumentHelper.createDocument();
Element employees = document.addElement("employees");
//第一个员工信息
Element employee = employees.addElement("employee");
employee.addAttribute("id", "gshzhou");
Element name = employee.addElement("name");
name.setText("gshzhou");
Element sex = employee.addElement("sex");
sex.setText("male");
Element age = employee.addElement("age");
age.setText("25");
//第二个员工信息
Element employee2 = employees.addElement("employee");
employee2.addAttribute("id", "mingr");
Element name2 = employee2.addElement("name");
name2.setText("mingr");
Element sex2 = employee2.addElement("sex");
sex2.setText("male");
Element age2 = employee2.addElement("age");
age2.setText("30");
try
{
Writer fileWrite = new FileWriter(path);
XMLWriter xmlWrite = new XMLWriter(fileWrite);
xmlWrite.write(document);
xmlWrite.close();
System.out.println("Dom4j生成xml成功。");
}
catch (IOException e)
{
System.out.println("Dom4j生成xml异常。" + e.getMessage());
}
}
//dom4j解析xml
public void parserXml(String fileName)
{
File inputXml = new File(fileName);
SAXReader saxReader = new SAXReader();
try
{
Document document = saxReader.read(inputXml);
Element employees = document.getRootElement();
for(Iterator i = employees.elementIterator(); i.hasNext(); )
{
Element employee = (Element)i.next();
for(Iterator j = employee.elementIterator(); j.hasNext(); )
{
Element node = (Element)j.next();
System.out.println(node.getName() + ":" + node.getText());
}
}
System.out.println("Dom4j解析成功.");
}
catch (DocumentException e)
{
System.out.println("dom4j解析xml异常:" + e.getMessage());
}
}
//Dom4j的一个亮点,使用xpath语法查找节点,快
public void xpathDom4j(String path)
{
SAXReader saxReader = new SAXReader();
try
{
Document document = saxReader.read(path);
Node root = document.selectSingleNode("/employees");
//Node root = document.getRootElement();
//取employees下id为gshzhou的节点
List list = root.selectNodes("employee[@id='gshzhou']");
System.out.println(list.size());
for(Object o : list)
{
Element e = (Element)o;
//attributeValue是读取节点的属性值
System.out.println("Node's attribute -> " + e.attributeValue("id"));
}
//取employees下所有的 employee节点
List list1 = root.selectNodes("employee");
//取employees节点下的employee节点下的name节点
List list2 = root.selectNodes("employee[@id='gshzhou']/name");
System.out.println("Node name -> " + ((Element)list2.get(0)).getName()); //输出子节点名字
System.out.println("Node value -> "+((Element)list2.get(0)).getText());//输出子节点内容
}
catch (DocumentException e)
{
e.printStackTrace();
}
}
}
说明:Dom4j用到了 dom4j-1.6.1.jar 和 jaxen-1.1-beta-6.jar 都能在下载的dom4j包中找到。