收藏信息.xml

<?xml version="1.0" encoding="GB2312" standalone="no"?><PhoneInfo>
<Brand id="" name="华为">
<Type name="U8650"/>
<Type name="HW123"/>
<Type name="HW321"/>
</Brand>
<Brand id="" name="苹果">
<Type name="iPhone4"/>
</Brand>
<Brand id="" name="三星"><type name="s120"/></Brand></PhoneInfo>

解析示例:

 import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator; import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; public class Dom4jParse {
public static Document document; //获取DOM
public static void getDom(){
SAXReader saxReader = new SAXReader();
try {
document = saxReader.read(new File("收藏信息.xml"));
} catch (DocumentException e) {
e.printStackTrace();
} } //获取所有节点信息
public static void showInfo(){
Element root = document.getRootElement();
for(Iterator itBrand=root.elementIterator();itBrand.hasNext();){
Element brand = (Element) itBrand.next();
System.out.println("品牌"+brand.attributeValue("name"));
for(Iterator itType=brand.elementIterator();itType.hasNext();){
Element type = (Element) itType.next();
System.out.println("\t型号"+type.attributeValue("name"));
}
} } //添加节点
public static void addNode(){
Element root = document.getRootElement();
Element eBrand = root.addElement("Brand");
eBrand.addAttribute("name", "诺基亚");
Element eType = eBrand.addElement("type");
eType.addAttribute("name", "直板");
saveXml("收藏信息.xml");
} //更新节点,添加ID属性
public static void updateNode(){
Element root = document.getRootElement();
int id=0;
for(Iterator iBrand=root.elementIterator();iBrand.hasNext();){
Element brand = (Element)iBrand.next();
id++;
brand.addAttribute("id", id+"");
}
saveXml("收藏信息.xml");
} //删除节点
public static void deleteNode(){
Element root = document.getRootElement();
for(Iterator iBrand=root.elementIterator();iBrand.hasNext();){
Element brand = (Element)iBrand.next();
if(brand.attributeValue("name").equals("诺基亚")){
brand.getParent().remove(brand);
}
}
saveXml("收藏信息.xml");
} //保存XML
public static void saveXml(String path){
//输出格式转换器
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK2312");
XMLWriter writer;
try {
writer = new XMLWriter(new FileWriter(path), format);
writer.write(document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
Dom4jParse dp = new Dom4jParse();
dp.getDom();
dp.showInfo(); } }
05-08 15:07