xml-java

1 篇文章 0 订阅

XML

创建一个xml

xml中标签是区分大小写的,严格要求嵌套与配对,可以加上css进行 展示

<?xml version="1.0" encoding="utf-8"  standalone="no"?> <!-- 这三个是按顺序的.standalone(不太理解),它的值为yes 和no,
找到的解释是
standalone 是可以去除的
值 no 表示这个 XML 文档不是独立的而是依赖于外部所定义的一个 DTD. 值 yes 表示这个 XML 文档是自包含的(self-contained).-->
<?xml-stylesheet type="text/css" href="people.css"?><!--引用css-->
<people>
    <person id="gy">
    <name>关羽</name>
    <nickName>武圣</nickName>
    <sex></sex>
      <favorite>看书--&lt;&lt;春秋&gt;&gt;--<![CDATA[<<春秋>>]]></favorite> <!--大于 &gt;小于&lt-->
    <describe>身长九尺,髯长二尺;面如重枣,唇若涂脂;丹凤眼,卧蚕眉,相貌堂堂,威风凛凛</describe>
    </person>
    <person id="dc">
     <name>貂蝉</name>
    <nickName>闭月</nickName>
    <sex></sex>
    <describe>年方二八,色伎俱佳</describe>              <!--&apos;单引号,&qout;双引号,也可以使用<![CDATA[]]>  原样输出-->
    </person>
</people>

people.css


name,nickName,sex,describe{
    display:block;
    font-size:20px;     
}
name{
    color:green;/*关羽的帽子据说是绿色的*/ /*font-color没有效果,用color*/
}
describe{
    font-color:red;
}

这里写图片描述

dom解析

dom解析器将文件转化为dom树存在内存中

这里写图片描述

读取

package com.bruce.test;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
 * @Author: hwq
 * @Description:com.bruce.test
 * @Date: Created in 1:38 2018/8/29
 * @Modifiy By:
 */
public class MyXMLTest {
    public static void main(String[] args) {
        pareXml("D:\\ideaDemo\\xmlDemo\\src\\main\\resources\\people.xml");
    }

    /**
     *@Description:
     * @Author: hwq
     * @Date: 2018/8/29 1:44
     */
    public static  void pareXml(String filepath){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=null;
        Document doc=null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(filepath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        NodeList personList = doc.getElementsByTagName("person");
        for(int i=0;i<personList.getLength();i++){
            Element e = (Element)personList.item(i);
            System.out.println("id:"+ e.getAttribute("id")); 
            System.out.println("name:"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
           //e.getElementsByTagName("name").item(0).getNodeValue(),这里必须先getFirstChild()得到文本节点然后再getNodeValue()
            System.out.println("nickName:"+e.getElementsByTagName("nickName").item(0).getFirstChild().getNodeValue());
//            System.out.println("favorite:"+e.getElementsByTagName("favorite").item(0).getFirstChild().getNodeValue());
            System.out.println("describe:"+e.getElementsByTagName("describe").item(0).getFirstChild().getNodeValue());
        }

    }
}

结果:

id:gy
name:关羽
nickName:武圣
describe:身长九尺,髯长二尺;面如重枣,唇若涂脂;丹凤眼,卧蚕眉,相貌堂堂,威风凛凛
id:dc
name:貂蝉
nickName:闭月
describe:年方二八,色伎俱佳

生成

package com.bruce.test;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.swing.text.html.HTML;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * @Author: hwq
 * @Description:com.bruce.test
 * @Date: Created in 2:23 2018/8/29
 * @Modifiy By:
 */
public class MyXMLTest2 {

    public static void main(String[] args) {
     createXMl("d:\\people2.xml");
    }
    public static void createXMl(String filePath){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=null;
        try {
             builder = factory.newDocumentBuilder();

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //新建document
        Document doc= builder.newDocument();
        //新建元素
        Element people = doc.createElement("people");
        Element person = doc.createElement("person");
        person.setAttribute("id","gy");
        Element name = doc.createElement("name");
        Element nickName = doc.createElement("nickName");
        Element favorite = doc.createElement("favorite");
        Element describe = doc.createElement("describe");
        //新建noteText,并添加到element中
        name.appendChild(doc.createTextNode("关羽"));
        nickName.appendChild(doc.createTextNode("武圣"));
        favorite.appendChild(doc.createTextNode("<<春秋>>"));
        describe.appendChild(doc.createTextNode("身长九尺,髯长二尺;面如重枣,唇若涂脂;丹凤眼,卧蚕眉,相貌堂堂,威风凛凛"));

        person.appendChild(name);
        person.appendChild(nickName);
        person.appendChild(favorite);
        person.appendChild(describe);
        people.appendChild(person);
        doc.appendChild(people);
        writeXML(filePath, doc);


    }

    private static void writeXML(String filePath, Document doc) {
        //写出
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer t=null;
        try {
            t = transformerFactory.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
        /**Transformer
         * This instance may then be used to process XML from a
         * variety of sources and write the transformation output to a
         * variety of sinks.
         */
        StreamResult result=new StreamResult(filePath);
        //充当转换结果的持有者,可以为 XML、纯文本、HTML 或某些其他格式的标记。

        DOMSource source=new DOMSource(doc);
        /**
         * **DOMSource
         * <p>Acts as a holder for a transformation Source tree in the
         * form of a Document Object Model (DOM) tree.</p>
         *
         */
       /* t.setOutputProperty(OutputKeys.ENCODING,"utf-8");*/
        try {
            t.transform(source,result);  //记住这个
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

结果

<?xml version="1.0" encoding="utf-8" standalone="no"?><people><person id="gy"><name>关羽</name><nickName>武圣</nickName><favorite>&lt;&lt;春秋&gt;&gt;</favorite><describe>身长九尺,髯长二尺;面如重枣,唇若涂脂;丹凤眼,卧蚕眉,相貌堂堂,威风凛凛</describe></person></people>

并不会换行,在一行上;

–声明:参考《Java Web开发实战经典》.(李兴华)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值