xml文件
<?xml version="1.0" encoding="UTF-8"?>
<Phonelnfo>
<Brand name="华为">
<Type name="U8650"/>
<Type name="HW123"/>
<Type name="HW321"/>
</Brand>
<Brand name="苹果">
<Type name="iPhone12"/>
</Brand>
<Brand name="oppo">
<Type name="R9SPlus"/>
</Brand>
<Brand name="oppo">
<Type name="R9SPlus"/>
</Brand>
</Phonelnfo>
Java文件
package xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import org.dom4j.Attribute;
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 Demo {
public static void main(String[] args) throws Exception {
// 在程序中获取xml文件的内容
// DOM解析--将xml文件中的内容读取到程序中
// 在程序中可以对文件进行新增和删除操作
File file = new File("src/File1.xml");
// 将xml中的所有内容获取到程序中
SAXReader reader = new SAXReader();
Document doc = reader.read(file); //doc就是xml文件
Element root = doc.getRootElement(); //获取根标签
List<Element> eles = root.elements(); //获取全部的子标签
for (Element ele : eles) {
String name = ele.getName(); //获取标签的名字
List<Attribute> attrs = ele.attributes();
Attribute attr = attrs.get(0); //获取Brand的属性值
String attrName = attr.getName(); //获取属性名
String attrValue = attr.getValue(); // 获取属性值
System.out.println("\t子元素是:"+name+",属性有:"+attrName+"对应的属性值是:"+attrValue+"子元素如下:");
// 获取Brand标签的子标签
List<Element> types = ele.elements(); //获取了所有的Type标签
for (Element type : types) {
List<Attribute> typeAttr = type.attributes(); //获取每一个type标签的属性
String typeAttrName = typeAttr.get(0).getName(); // type标签的属性名
String typeAttrValue = typeAttr.get(0).getValue(); // type标签的属性值
System.out.println("\t\t标签名:"+type.getName()+",属性有:"+typeAttrName+" 对应的属性值是:"+typeAttrValue);
}
}
// 2:新增1个品牌 ,oppo,其实就是为root添加一个子标签
Element Brand = root.addElement("Brand"); // 添加了一个子标签
Brand.addAttribute("name", "oppo"); // <Brand name="oppo">
Element type = Brand.addElement("Type");
type.addAttribute("name", "R9SPlus");
// 持久化
OutputStream out = new FileOutputStream(file); // doc要写到哪个文件中
OutputFormat format = OutputFormat.createPrettyPrint(); // 按照之前文档格式进行输出
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
writer.flush();
writer.close();
System.out.println("over");
}
}