码迷,mamicode.com
首页 > 其他好文 > 详细

XML解析

时间:2018-03-10 18:47:07      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:元素   gen   jar包   attr   bytearray   sax   out   生成   err   

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(); }
}

 

 

 

XML解析

标签:元素   gen   jar包   attr   bytearray   sax   out   生成   err   

原文地址:https://www.cnblogs.com/northern-light/p/8541149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!