Java中XML读写操作

最近做项目遇到了对XML读写上的问题,经过上网查阅研究,发现了一个很好的包:org.dom4j。jar包下载地址于是自己封装了一个XML读写类。以下就是我封装的类。

首先定义了一个类名:XMLHandle

public class XMLHandle {
    public static void main(String[] args) {
        
    }

    private String path="";
    private Document data=null;
    private Element element=null;

    public XMLHandle() {
    }
    //通过xml文件地址初始化
    public XMLHandle(String path) {
        this.path=path;
    }

    public String getPath() {
        return path;
    }

    public Document getData() {
        return data;
    }

    public Element getElement() {
        return element;
    }

    
}

其中地址的书写例子为:../Project/xml/test.xml,其中Project位项目工程文件夹

接下来是创建xml文件函数
//创建xml文件,空文件
    public boolean createXML(String filename){
        Document document = DocumentHelper.createDocument();
        Element rootElement = document.addElement(tablename);

        Element dictElement =  rootElement.addElement("dictionary");
        Element DWElement1 =  rootElement.addElement("DW");
        try{
            XMLWriter output = new XMLWriter(
                    new FileWriter( new File(filename) ));
            output.write( document );
            output.close();
            return true;
        }
        catch(
                IOException e){System.out.println(e.getMessage());
                return false;
        }

    }
//通过Hashmap创建一个xml文件
public void createXML(String filename,HashMap<String,String> map,String rootNodeName) throws Exception {
        Document document = DocumentHelper.createDocument(); 
        Element rootElement = document.addElement(rootNodeName);   
        ArrayList<String> keyList=new ArrayList<>(map.keySet());
        for(int i=0;i<keyList.size();++i){
            Element valElement = rootElement.addElement(keyList.get(i));
            valElement.setText(map.get(keyList.get(i)));
        }
        XMLWriter output = new XMLWriter(
                new FileWriter( new File(filename) ));
        output.write( document );
        output.close();
    }

//通过Hashmap(含属性)创建一个xml文件
public void createXML(String filename,HashMap<Hashmap<String,String>,String> map,String rootNodeName) throws Exception {
        Document document = DocumentHelper.createDocument(); 
        Element rootElement = document.addElement(rootNodeName);   
        Iterator iter = map.entrySet().iterator();
      while (iter.hasNext()) {
          Map.Entry entry = (Map.Entry) iter.next();
          Hashmap<String,String> attrmap = entry.getKey();
          String val = entry.getValue();
            Element valElement = rootElement.addElement("val");
            valElement.addAttribute(attrmap.get("attrName"), attrmap.get("attrValue"));
            valElement.setText(val);
        }
            XMLWriter output = new XMLWriter(
                new FileWriter( new File(filename) ));
            output.write( document );
            output.close();
        
    }

接下来是读xml文件

//加载本地XML文件
    public  Document LoadXML(String path){
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(path);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return document;
    }
   
    //读xml文件内容并输出
    public void readXML(String path){
        data=LoadXML(path);
        //获取根节点元素对象
        element = data.getRootElement();
        //遍历所有的元素节点
        listAllNodes(element);
    }
    //将xml文件的内容转换为Hashmap
    /*public HashMap xmlToHashMap(String path){
        data=LoadXML(path);
        element = data.getRootElement();
        HashMap<String,Integer> dictionary =new HashMap<>();
        xmlElementToHashmap_url(element,dictionary);
        return dictionary;
    }*/
    //将xml文件的内容转换为Hashmap
    public HashMap xmlToHashMap(String path,String key,String type,HashMap dictionary){
        data=LoadXML(path);
        element = data.getRootElement();
        xmlElementToHashmap_url(element,key,type,dictionary);
        return dictionary;
    }

    /**
     * 遍历当前节点元素下面的所有(元素的)子节点
     *
     * @param node
     */
    public void listAllNodes(Element node) {
        System.out.println("当前节点的名称::" + node.getName());
        // 获取当前节点的所有属性节点
        List<Attribute> list = node.attributes();
        // 遍历属性节点
        for (Attribute attr : list) {
            System.out.println(attr.getText() + "-----" + attr.getName());
        }

        if (!(node.getTextTrim().equals(""))) {
            System.out.println("文本内容::::" + node.getText());
        }

        // 当前节点下面子节点迭代器
        Iterator<Element> it = node.elementIterator();
        // 遍历
        while (it.hasNext()) {
            Element e = it.next();
            listAllNodes(e);
        }
    }
    //treeUrl位xml节点,例如/root/dict/*
    public void xmlElementToHashmap_url(Document document,String treeUrl,HashMap dictionary) {

        List list = document.selectNodes(treeUrl);
        Iterator iter = list.iterator();
        while (iter.hasNext()) {

            Element el = (Element) iter.next();
            // 获取当前节点的所有属性节点
            List<Attribute> sttrlist = el.attributes();
            // 遍历属性节点
            for (Attribute attr : sttrlist) {
                if (!(el.getTextTrim().equals(""))) {
                    dictionary.put(attr.getText(), el.getText());
                }
            }

        }
    }

接下来是修改xml文件,其中包括对现有节点修改和增加节点

public void modifyXML(Document document,String filename,String treeUrl,String value) throws Exception {
        Element e = (Element)document.selectSingleNode(treeUrl);
        e.setText(value);
        XMLWriter output = new XMLWriter(
                new FileWriter( new File(filename) ));
        output.write( document );
        output.close();
    }

    //通过Hashmap写入xml文件
    public void HashmapToXml(Document document,String filename,String treeUrl,HashMap<String,String> map) throws Exception {
        Element node = (Element)document.selectSingleNode(treeUrl);
        ArrayList<String> keyList=new ArrayList<>(map.keySet());
        for(int i=0;i<keyList.size();++i){
            Element valElement = node.addElement("val");
            valElement.addAttribute("key", keyList.get(i));
            valElement.setText(map.get(keyList.get(i)));
        }
        XMLWriter output = new XMLWriter(
                new FileWriter( new File(filename) ));
        output.write( document );
        output.close();
    }

 

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值