package com.cn;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXml {
public ReadXml() {
// 得到Dom解析工厂
DocumentBuilderFactory domfactory = DocumentBuilderFactory
.newInstance();
try {
// 取得dom解析器
DocumentBuilder docBilder = domfactory.newDocumentBuilder();
// 将xml文件读入输入流
InputStream in = new FileInputStream("F://tes.xml");
FileWriter fw = new FileWriter("F://waa.xml");
// 解析xml输入流
Document doc = docBilder.parse(in);
// 在DOM中取得xml的根节点
Element root = doc.getDocumentElement();
// 得到子节点
NodeList students = root.getChildNodes();
// 遍历子节点
if (students != null) {
for (int i = 0; i < students.getLength(); i++) {
fw.write("<?xml version=\"1.0\"encoding=\"UTF-8\"?>");
Node student = students.item(i);
// 判断是否有属性
if (student.getNodeType() == Node.ELEMENT_NODE) {
fw.write("\n<students>");
String sn = student.getAttributes().getNamedItem("sn")
.getNodeValue();
fw.write("\n<student sn="+sn+"> ");
System.out.println("sn-------------"+sn);
}
// 轮训子节点
for (Node node = student.getFirstChild(); node != null; node = node
.getNextSibling()) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName().equals("name")) {
String name = node.getNodeValue();
System.out.println("name--------------" + name);
String name1 = node.getFirstChild()
.getNodeValue();
System.out.println("name1--------------"
+ name1);
fw.write("\n<name>"+name1+"\n</name>");
}
if (node.getNodeName().equals("age")) {
String age = node.getFirstChild()
.getNodeValue();
System.out.println("age---------" + age);
fw.write("\n<age>"+age+"\n</age>");
fw.write("\n</students>");
}
}
}
}
}
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
ReadXml rd = new ReadXml();
}
}