dom4j操作xml 博客分类: XML dom4jxmljava
导入dom4j.jar包
创建xml文件
XMLWriter writer = null;// 声明写XML的对象
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");// 设置XML文件的编码格式
String filePath = "F://student.xml";//保存xml文件路径
File file = new File(filePath);
Document _document = DocumentHelper.createDocument();
Element _root = _document.addElement("学生信息");//----------根
Element student = _root.addElement("学生");
Element _id = student.addElement("编号");
_id.setText("001");
Element _name = student.addElement("姓名");
_name.setText("灰机");
Element _age = student.addElement("年龄");
_age.setText("18");
for(int i=0;i<5;i++)
{
Element _student = _root.addElement("record");
_student.addAttribute("sid", "00"+i);
_student.addAttribute("phone", "1100"+i);
}
try
{
writer = new XMLWriter(new FileWriter(file), format);
writer.write(_document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("操作结束! ");
生成结果图:
读取xml文件
SAXReader reader = new SAXReader();
String filePath = "f://student.xml";
File file = new File(filePath);
Document document;
try {
document = reader.read(file);
Element root = document.getRootElement();// 得到根节点
/*Element database = (Element)root.selectSingleNode("//学生信息/学生");
List list = database.elements(); //得到database元素下的子元素集合
for(Object obj:list){
Element element = (Element)obj;
//getName()是元素名,getText()是元素值
System.out.println(element.getName()+": "+element.getText());
}*/
List nodes = root.elements("学生");
for (Iterator it = nodes.iterator(); it.hasNext();) {
Element elm = (Element) it.next();
for(Iterator it2=elm.elementIterator();it2.hasNext();){
Element elel=(Element)it2.next();
System.out.println(elel.getName()+":"+elel.getText()+":");
}
}
for (Iterator i = root.elementIterator("record"); i.hasNext();) //对所有record子节点进行遍历
{
Element student = (Element) i.next();
//if (student.attributeValue("sid").equals("001")) //如果record属性sid的值等于001
for(Iterator it= student.attributeIterator();it.hasNext();)//获取record节点的所有属性
{
Attribute attribute = (Attribute) it.next();
String name=attribute.getName();//获取属性名
String text=attribute.getText();//获取属性值
System.out.println(name + " :"+text);
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
推荐阅读
-
dom4j创建xml和读取xml的demo 博客分类: java基础 dom4jxmlSAXReader
-
Java操作XML文件 dom4j 篇 转 博客分类: JAVA-XML xmldom4j
-
dom4j解释XML 博客分类: Java xmldom4j
-
dom4j解析xml字符串 博客分类: 公用方法 dom4j
-
dom4j操作xml 博客分类: XML dom4jxmljava
-
JSON 博客分类: xml及相关 jsonJavaScriptIBMXMLIDEA
-
在xml中使用CSS和XSL 博客分类: XML cssxsl
-
XML文件转换成 HTML 博客分类: XML xslxmlhtmljava
-
XML与XSLT(续) 博客分类: XML xmlxsl
-
XSL介绍 博客分类: Ajax/XML/JSON/XSL xsl