package com.hxgd.ms.readfile; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; //生成xml格式的字符串 public class CreateXml { /* 依赖 dom4j
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
*/
public static void main(String[] args) { //生成xml格式的字符串
<?xml version="1.0" encoding="UTF-8"?>
<User><name>张三</name><age>18</age><gender sex="男">男</gender></User>
Document document2 = DocumentHelper.createDocument();
Element ele = document2.addElement("User"); Element elename = ele.addElement("name"); elename.setText("张三"); Element eleage = ele.addElement("age"); eleage.setText("18"); Element elegender = ele.addElement("gender"); elegender.setAttributeValue("sex", "男"); elegender.setText("男"); String asXML2 = document2.asXML(); System.err.println(asXML2); } }
//解析xml文件或者解析xml格式的字符蠢
public static void readXml() { //引入jar包 //创建解析器 //创建SAXReader对象读取.xml文件 SAXReader sax=new SAXReader(); //获取dom树 Document document = null; try { //读取XML文件 document = sax.read(new File("product.xml")); } catch (DocumentException e) { e.printStackTrace(); } /*解析 xml字符串 * String xml ="xml字符串"; try { Document document2 = sax.read(new ByteArrayInputStream(xml.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }*/ //获取根元素 Element rootElement = document.getRootElement(); //获取所有子元素 Iterator<Element> iterator = rootElement.elementIterator(); while(iterator.hasNext()){ //拿到属性方法一 Element element = iterator.next(); // Attribute attribute = element.attribute("ID"); // String value = attribute.getText(); // System.err.println(attribute.getName()+"--->"+value); //拿到属性方法二 List<Attribute> list = element.attributes(); for(Attribute a:list){ System.out.println(a.getName()+"-----"+a.getText()); } Iterator<Element> iterator2 = element.elementIterator(); while(iterator2.hasNext()){ Element next = iterator2.next(); System.out.println(next.getName()+"-->"+next.getText()); } System.out.println(); }
}