package com.chinasoft.parsexml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
public class W3CParseXml {
public static void main(String[] args) {
read();
}
private static void read() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
InputStream in = W3CParseXml.class.getClassLoader()
.getResourceAsStream("test.xml");
Document doc = builder.parse(in);
// root <university>
Element root = doc.getDocumentElement();
if (root == null) {
return;
}
System.err.println(root.getAttribute("name"));
// all college node
NodeList collegeNodes = root.getChildNodes();
if (collegeNodes == null)
return;
for (int i = 0; i < collegeNodes.getLength(); i++) {
Node college = collegeNodes.item(i);
if (college != null
&& college.getNodeType() == Node.ELEMENT_NODE) {
System.err.println("\t"
+ college.getAttributes().getNamedItem("name")
.getNodeValue());
// all class node
NodeList classNodes = college.getChildNodes();
if (classNodes == null)
continue;
for (int j = 0; j < classNodes.getLength(); j++) {
Node clazz = classNodes.item(j);
if (clazz != null
&& clazz.getNodeType() == Node.ELEMENT_NODE) {
System.err.println("\t\t"
+ clazz.getAttributes()
.getNamedItem("name")
.getNodeValue());
// all student node
NodeList studentNodes = clazz.getChildNodes();
if (studentNodes == null)
continue;
for (int k = 0; k < studentNodes.getLength(); k++) {
Node student = studentNodes.item(k);
if (student != null
&& student.getNodeType() == Node.ELEMENT_NODE) {
System.err.print("\t\t\t"
+ student.getAttributes()
.getNamedItem("name")
.getNodeValue());
System.err.print(" "
+ student.getAttributes()
.getNamedItem("sex")
.getNodeValue());
System.err.println(" "
+ student.getAttributes()
.getNamedItem("age")
.getNodeValue());
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void wrire() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream is = W3CParseXml.class.getResourceAsStream("test.xml");
Document document = builder.parse(is);
// root (university)
Element root = document.getDocumentElement();
if (root == null) {
return;
}
// 修改属性
root.setAttribute("name", "tsu");
NodeList collageNodes = root.getChildNodes();
if (collageNodes != null) {
for (int i = 0; i < collageNodes.getLength(); i++) {
// 删除节点
Node collage = collageNodes.item(i);
if (collage.getNodeType() == Node.ELEMENT_NODE) {
String collageName = collageNodes.item(i)
.getAttributes().getNamedItem("name")
.getNodeValue();
if ("c1".equalsIgnoreCase(collageName)
|| "c2".equalsIgnoreCase(collageName)) {
root.removeChild(collage);
} else if ("c3".equalsIgnoreCase(collageName)) {
Element newChild = document.createElement("class");
newChild.setAttribute("name", "c4");
collage.appendChild(newChild);
}
}
}
}
Element addCollege = document.createElement("college");
addCollege.setAttribute("name", "c5");
root.appendChild(addCollege);
Text text = document.createTextNode("text");
addCollege.appendChild(text);
// 将修改后的文档保存到文件
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transFormer = transFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
File file = new File("src/dom-modify.xml");
if (file.exists()) {
file.delete();
}
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
StreamResult xmlResult = new StreamResult(out);
transFormer.transform(domSource, xmlResult);
System.out.println(file.getAbsolutePath());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.chinasoft.parsexml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jParseXml {
private static final String filePath = "src/text-modify.xml";
public static void main(String[] args) {
write(filePath);
read();
}
/**
*
* @param outFile
*/
public static void write(String outFile) {
try {
// 创建文档对象
Document document = DocumentHelper.createDocument();
// 创建节点
Element universtity = document.addElement("university");
// 给节点添加属性
universtity.addAttribute("name", "fudan");
// 添加注释
universtity.addComment("这是根节点");
for (int i = 0; i < 3; i++) {
Element collage = universtity.addElement("collage");
collage.addAttribute("name", "张明" + i);
collage.addText("text");
}
// collage.setText("text");
// 定义xml写入格式
OutputFormat format = new OutputFormat();
format.setIndent(true);
format.setEncoding("GBK");
format.setNewlines(true);
File file = new File(outFile);
if (file.exists()) {
file.delete();
}
file.createNewFile();
XMLWriter out = new XMLWriter(new FileWriter(file), format);
out.write(document);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解析xml文件
*/
public static void read() {
try {
SAXReader reader = new SAXReader();
InputStream is = Dom4jParseXml.class
.getResourceAsStream("test.xml");
org.dom4j.Document doc = reader.read(is);
// 获取根节点
Element university = doc.getRootElement();
readNode(university, " ");
} catch (DocumentException e) {
e.printStackTrace();
}
}
@SuppressWarnings( { "unchecked", "unchecked" })
private static void readNode(Element root, String prefix) {
if (root == null) {
return;
}
// 获取属性
List<Attribute> attrs = root.attributes();
if (attrs != null && attrs.size() > 0) {
System.err.print(prefix);
for (Attribute attr : attrs) {
System.err.print(attr.getValue() + " ");
}
System.err.println();
}
// 获取他的子节点
List<Element> childNodes = root.elements();
if (childNodes == null) {
return;
} else {
prefix += "\t";
for (Element e : childNodes) {
readNode(e, prefix);
}
}
}
}