一、xml文件在Java中的转换

  对象相互转换:xml、document、String、json

  技术实现:jdom、javax.xml.parsers(java标准API)、dom4j

  Document:操作xml的顶级入口

二、dom4j

  1、获取Document

     手动创建Document

/**
     * Document
     * @return
     */
    public Document getDocument()
    {
        //主动创建Document对象
        Document doc = DocumentHelper.createDocument();
        //创建根节点,根节点只能一个
        Element xml = doc.addElement("xml");
        
        //根节点创建两个属性
        xml.addAttribute("method", "testXml");
        xml.addAttribute("type", "test");
        
        //创建两个二级节点
        Element user = xml.addElement("user");
        Element bookStore = xml.addElement("bookstore");
        
        //user创建子节点
        user.addAttribute("isActive", "true");
        user.addAttribute("userId", "2012117153");
        Element name = user.addElement("name");
        name.setText("刘广平");
        Element age = user.addElement("age");
        age.setText("18");
        Element sex = user.addElement("sex");
        sex.setText("男");
        Element location = user.addElement("location");
        location.setText("广东深圳");
        
        //书店创建
        for(int i = 1;i < 5;i++)
        {
            Element book = bookStore.addElement("book"+i);
            Element bookName = book.addElement("bookName");
            bookName.setText("书本"+i);
            Element bookPrice = book.addElement("bookPrice");
            bookPrice.setText(i+"元");
            Element author = book.addElement("author");
            author.setText("作者"+i);
        }
        
        return doc;
    }

    String转Document

/**
     * 读取xml格式的String字符串,获取Document
     * @param text
     * @return
     */
    public static Document getDocumentByText(String text)
    {
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

  读取本地xml

/**
     * 通过文件流生成Document
     * @param io
     * @return
     */
    public static Document getDocumentByIo(InputStream io)
    {
        Document doc = null;
        try {
            SAXReader reader = new SAXReader();
            doc = reader.read(io);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

  读取流

/**
     * 通过文件流生成Document
     * @param io
     * @return
     */
    public static Document getDocumentByIo(InputStream io)
    {
        Document doc = null;
        try {
            SAXReader reader = new SAXReader();
            doc = reader.read(io);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

  2、Document生成xml文件,并存储

/**
     * 通过document创建xml
     * @param doc
     */
    public static void generateXml(Document doc)
    {
        OutputFormat format = new OutputFormat("", true, "UTF-8");
        format.setIndent(true);
        XMLWriter writer;
        try {
            //可以配置存储路径,只有文件名,保存在工程路径统计目录
            writer = new XMLWriter(new FileOutputStream("src/main/java/xml/test.xml"),format);
            writer.write(doc);
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  3、Document转String:asXML(),转换后的结果是带

System.out.println("document:"+doc.asXML());
        System.out.println("name:"+name.asXML());

 

    转换后的结果

xml2Json:{"bookstore":{"book2":{"author":"作者2","bookPrice":"2元","bookName":"书本2"},"book1":{"author":"作者1","bookPrice":"1元","bookName":"书本1"},"book4":{"author":"作者4","bookPrice":"4元","bookName":"书本4"},"book3":{"author":"作者3","bookPrice":"3元","bookName":"书本3"}},"user":{"sex":"男","name":"刘广平","location":"广东深圳","age":"18"}}

  4、Document常用操作

Document doc = new DocumentDemo().getDocument();
        
        //获取根目录
        Element root = doc.getRootElement();
        
        //获取节点本身信息
        String name = root.getName(); //获取节点名
        String value1 = root.getStringValue(); //获取节点值
        String value2 = root.getText(); //获取节点值
        String value3 = root.getTextTrim();//获取节点值
        
        //获取节点属性
        int attrNum = root.attributeCount(); //属性总个数
        Attribute attr = root.attribute("0");//通过下标获取属性对象
        Attribute attr1 = root.attribute("id");//通过属性名获取属性对象
        
        //批量获取子节点
        @SuppressWarnings("unchecked")
        List<Element> eles = root.elements();
        
        //批量获取属性
        @SuppressWarnings("unchecked")
        List<Attribute> attrs = root.attributes();
        
        //添加子节点
        root.addElement("addElement", "addValue");
        root.addAttribute("addAttribute", "addVlaue");
        
        //删除子节点
        Element element = root.element("addElement");
        root.remove(element);
        
        //修改节点
        Element nameElement = root.element("name");
        nameElement.setText("newName");

 

三、Jdom操作XML

 

 

四、w3c操作XML:Java自带

  1、生成Document

/**
     * 创建DOM树:
     * 1、创建DocumentBuilderFactory对象
     * 2、通过DocumentBuilderFactory对象创建DocumentBuilder对象
     * 3、通过DocumentBuilder对象的newDocument()方法创建一个Document对象,该对象代表一个XML文件
     * 4、通过Document对象的createElement()方法创建根节点
     * 5、通过Document对象的createElement()方法创建N个子节点,并为他们赋值,再将这些子节点添加到根节点下
     * 6、将根节点添加到Document对象下
     */
    public static Document getDocument()
    {
        Document doc = null;
        try {
            //创建DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //创建DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.newDocument();
            //创建根节点
            Element root = doc.createElement("bookStore");
            
            //创建子节点
            Element book = doc.createElement("book");
            book.setAttribute("id", "book1");
            //创建子节点属性
            Element name = doc.createElement("name");
            name.setTextContent("安徒生童话");
            book.appendChild(name);
            Element author = doc.createElement("author");
            author.setTextContent("捉着");
            book.appendChild(author);
            
            //根节点添加子节点
            root.appendChild(book);
            
            //根节点添加到document
            doc.appendChild(root);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return doc;
    }

  

  存储XML文件

/**
     * DOM树转换为XML文件:
     * 创建TransformerFactory类的对象
     * 通过TransformerFactory创建Transformer对象
     * 使用Transformer对象的transform()方法将DOM树转换为XML文件。
     *         (该方法有两个参数,第一个参数为源数据,需要创建DOMSource对象并将Document加载到其中;
     *           第二个参数为目的文件,即要生成的XML文件,需要创建StreamResult对象并指定目的文件)
     */
    public static void transforXML(Document doc)
    {
        try {
            //创建TransformerFactory
            TransformerFactory tff = TransformerFactory.newInstance();
            //创建Transformer
            Transformer tf = tff.newTransformer();
            // 设置输出数据时换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            //创建
            tf.transform(new DOMSource(doc), new StreamResult(new File("tt.xml")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

  1、Jdom

 

  2、dom4j

 

  3、javax.xml.parsers