前2天大概翻了下SE,今天开始看了下DOM4J关于XML的处理,发现java真是一个挺好用的工具呢。明天考6级,果然还是随缘过了,反正……应该不重要吧!!!!!
1.关于读取XML的操作
//基本语法
package cn.xml.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;
public class ReadXml {
/**
* 读取XML内容******* 1.读取文件,SAXReader read, Document doc 2.获取根元素Element
* doc.getRootElement(); 3.Iterator<Node> it接受存储内容 Iterator
* <Node> ele.nodeIterator() 4.遍历Iterator, boolean it.hasNext(),Node
* it.next() 4.5 获取名字 String it.next().getName()
*/
public void readXml() throws DocumentException {
// 得到节点信息
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("pom.xml"));
// -----得到当前节点所有子对象----相当于XML根节点----不包括下层节点
Iterator<Node> it = doc.nodeIterator();
ArrayList<String> al = new ArrayList<>();
while (it.hasNext()) {
Node n = it.next(); // 取出节点
al.add("doc.node: " + n.getName());
// 继续取下层节点。。只有标签才有子节点
// 判断是否是标签
if (n instanceof Element) {
Element ele = (Element) n;
Iterator<Node> ie = ele.nodeIterator();
while (ie.hasNext()) {
al.add("node.element: " + ie.next().getName());
}
}
}
for (String s : al)
System.out.println(s);
}
/**
* ***********遍历xml中所有Element/***********************
*
*/
public static ArrayList<String> al = new ArrayList<>();
public void readXml2() throws DocumentException {
// 得到节点信息
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("pom.xml"));
// 将根标签存储到Elememt rootEle
Element rootEle = doc.getRootElement();
getChildElememt(rootEle);
for (String s : al)
System.out.println(s);
}
private void getChildElememt(Element e) {
Iterator<Node> it = e.nodeIterator();
while (it.hasNext()){
Node node=it.next();
if(node instanceof Element){
al.add(node.getName());
getChildElememt((Element)node);
}
}
}
/*******
* ***************获取标签
* @throws DocumentException ***************
*/
@Test
public void ReadXML3() throws DocumentException{
//1.读取文档
SAXReader read=new SAXReader();
Document doc=read.read(new File("pom.xml"));
//2.获取根标签
Element rootEle=doc.getRootElement();
//3.1得到指定名称根标签下第一个子标签
Element buildEle=rootEle.element("build");
//3.1.1 获取该标签下所有子标签
List<Element> buildEleChild=buildEle.elements();
for(Element e:buildEleChild)
System.out.println(e.getName());
//3.2 得到当前标签下指定名称所有子标签
Iterator<Element> groupEleI=rootEle.elementIterator("groupId");
while(groupEleI.hasNext())
System.out.println(groupEleI.next().getName());
//4.得到当前标签下所有子标签
List<Element> list=rootEle.elements();
//方法a
for(Element s:list)
System.out.println(s.getName());
// //方法b
// for(int i=0;i<list.size();i++){
// System.out.println(list.get(i).getName());
// }
// //方法c
// Iterator<Element> iterator = list.iterator();
// while(iterator.hasNext())
// System.out.println(iterator.next().getName());
//5. 获取深层次标签,只能一层层获取。获取文本.getText()
Element artIdEle=rootEle.element("build").element("plugins")
.element("plugin").element("artifactId");
System.out.println(artIdEle.getText());
//6. 获取指定标签指定属性值
// //1.属性对象
// Attribute att=rootEle.attribute("schemaLocation");
// System.out.println(att.getName()+"="+att.getValue());
//
// //2,直接查找
// System.out.println(rootEle.attributeValue("schemaLocation"));
//3.得到所有属性返回值
List<Attriute> attributes = rootEle.attributes();
for(Attribute i:attributes)
System.out.println(i.getName()+"="+i.getValue());
//7.获取得到指定标签文本 .elementTe
xt("标签名") 标签名.getText();
System.out.println(rootEle.element("build").element("plugins")
.element("plugin").elementText("version"));
}
}
//一个封装类pomdependencies.java
package cn.xml.test;
public class PomDependencies {
private String GroupId;
private String ArtifactId;
private String Version;
private int Tid;
public int getTid() {
return Tid;
}
public void setTid(int tid) {
Tid = tid;
}
public String getGroupId() {
return GroupId;
}
public void setGroupId(String groupId) {
GroupId = groupId;
}
public String getArtifactId() {
return ArtifactId;
}
public void setArtifactId(String artifactId) {
ArtifactId = artifactId;
}
public String getVersion() {
return Version;
}
public void setVersion(String version) {
Version = version;
}
@Override
public String toString() {
return "PomDependencies [Tid=" + Tid + ", GroupId=" + GroupId + ", ArtifactId=" + ArtifactId + ", Version="
+ Version + "]";
}
}
//主
package cn.xml.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class PomShow {
public static void main(String[] args) throws DocumentException {
ArrayList<PomDependencies> al=new ArrayList<>();
SAXReader sr=new SAXReader();
Document doc=sr.read(new File("pom.xml"));
Element depElem=doc.getRootElement().element("dependencies");
List<Element> el = depElem.elements();
int a=1;
for(Element i:el){
PomDependencies pd=new PomDependencies();
pd.setTid(a);
pd.setGroupId(i.elementText("groupId"));
pd.setArtifactId(i.elementText("artifactId"));
pd.setVersion(i.elementText("version"));
al.add(pd);
a++;
}
System.out.println(al.get(1));
for(PomDependencies i:al)
System.out.println(i.toString());
}
}
2.关于XML的修改
//XMLWrite.java
package cn.xml.write;
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlWrite {
public static void main(String[] args) throws Exception{
//1,读取一个XML文件
Document doc=new SAXReader().read(new File("src/test.xml"));
//2.修改XML文件
//2.1输出格式
OutputFormat of1=OutputFormat.createCompactFormat(); //无换行空格
OutputFormat of2=OutputFormat.createPrettyPrint(); //有换行空格
// of1.setEncoding("GBK"); //改变编码格式
//2.以字节流的方式保存到所指定文件,到指定目录
FileOutputStream fo=new FileOutputStream("src/xw.xml");
//3.创建写出对象
XMLWriter xw=new XMLWriter(fo);
// XMLWriter xw=new XMLWriter(fo,of1); //带输出格式
//4.写入对象
xw.write(doc);
//5.关闭流
xw.close();
}
}
//XMLEx.java
package cn.xml.write;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.SAXWriter;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class XmlEx {
/**
* 创建增加XML内容
* @throws IOException
*/
public void XmlAdd() throws IOException{
//创建文档---并写入
Document doc=DocumentHelper.createDocument();
//加入标签,并以根标签传入rootEle
Element rootEle= doc.addElement("ContactList");
//在根标签内加入Contact标签
Element conEle=rootEle.addElement("Contact");
//在Contact标签下再加入标签,写入内容
conEle.addElement("name").addText("xiaoli");
conEle.addElement("telephone").addText("1123456789");
//增加属性
conEle.addAttribute("id", "001");
FileOutputStream fo=new FileOutputStream("src/XmlWrite.xml");
OutputFormat of=OutputFormat.createPrettyPrint();
of.setEncoding("utf-8");
XMLWriter xw=new XMLWriter(fo,of);
xw.write(doc);
xw.close();
}
/**
* 修改XML内容
* @throws DocumentException
* @throws IOException
*/
@Test
public void XmlChange() throws DocumentException, IOException{
Document doc=new SAXReader().read(new File("src/XmlWrite.xml"));
Element conEle=doc.getRootElement().element("contact1");
/**
* 修改属性值
* 1.找到标签
* 2.找到属性对象
* 3.修改
*/
//1.修改
// Attribute att=conEle.attribute("id");
// att.setValue("002");
//2.或者增加同名属性修改
conEle.addAttribute("id", "004");
/**
* 修改节点名
*/
// conEle.setName("contact1");
/**
* 修改文本名
*/
//conEle.element("xiaoming").setName("name");
conEle.element("name").setText("xiaoming");
/**
* 删除标签
*/
try {
conEle.element("telephone").detach();
} catch (Exception e) {
}
/**
* 删除属性
*/
conEle.attribute("id").detach();
FileOutputStream fo=new FileOutputStream("src/XmlWrite.xml");
XMLWriter xw=new XMLWriter(fo);
xw.write(doc);
xw.close();
}
}
- 关于XPath
package cn.xpath.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XpathDemo {
/**
* xPath方法
* 1.List<node> selectNodes("xpath 表达式");
* 2.Node selectSingleNode("xpath 表达式");
* @throws DocumentException
* @throws IOException
*/
//为Dependency增加属性id=001……修改id=2标签下的groupId值
public static void main(String[] args) throws DocumentException, IOException {
Document doc=new SAXReader().read(new File("src/pomcopy.xml"));
List<Element> list=doc.selectNodes("//dependency");
int a=1;
for(Element i:list){
i.addAttribute("id",String.valueOf(a));
a++;
}
Element e=(Element) doc.selectSingleNode("//dependency[@id='2']/groupId");
e.setText("it's a test");
FileOutputStream fo=new FileOutputStream("src/pomcopy.xml");
XMLWriter xw=new XMLWriter(fo);
xw.write(doc);
xw.close();
}
}