package util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class getXML {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("/home/mfkwfc/catalog.xml"));
Element rootElement = document.getRootElement();
System.out.println(rootElement.getName());//读取根节点
for (Iterator i = rootElement.elementIterator(); i.hasNext();) {//获得根节点下的最大节点数,并循环。
//获得子节点
Element element = (Element) i.next();
System.out.println(element.getName());//读取根节点下的K
//System.out.println(element.getName()+"=="+element.getText());
for (Iterator j = element.attributeIterator(); j.hasNext();) {//这里是获取他title的值并循环出来
Attribute attribute = (Attribute) j.next();
System.out.println(attribute.getName() + "===" + attribute.getValue());//获得他的title的K AND V
}
//获得子节点下面的子节点
for (Iterator k = element.elementIterator(); k.hasNext();) {//获得根节点下的子节点下的子节点。
Element subElement = (Element) k.next();
System.out.println(subElement.getName()+"----"+subElement.getText());
if(subElement.getText().equals("abc"))//修改代码。修改完后记得再重新写回文件。。
{
subElement.setText("==");
}
for (Iterator l = subElement.attributeIterator(); l.hasNext();) {//获得子节点下面的title属性。。
Attribute subAttribute = (Attribute) l.next();
System.out.println(subAttribute.getName() + "===" + subAttribute.getValue());
}
}
//修改后重新写回文件
try {
XMLWriter xml=new XMLWriter(new FileWriter(new File("/home/mfkwfc/catalog.xml")));
xml.write(document);
xml.close();
} catch (IOException e) {
System.out.println("写入失败");
e.printStackTrace();
}
}
}
}
package util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
public class setXML {
/*
* 简洁版
*/
public static void main(String[] agrs){
Document docu=DocumentHelper.createDocument();
Element elem=docu.addElement("no2");
elem.addComment("zhushi");
Element el=elem.addElement("no1");
el.addAttribute("title","nimei");
el.addText("good");
try {
XMLWriter xml=new XMLWriter(new FileWriter(new File("/home/mfkwfc/catalog.xml")));
xml.write(docu);
xml.close();
} catch (IOException e) {
System.out.println("写入失败");
e.printStackTrace();
}
}
}