• Java操作XML


    问题描述:

            Java操作XML,包括增删查改、创建、删除基本操作

    参考资料:

      http://www.cnblogs.com/ITEagle/archive/2010/03/03/1677431.html 

    问题解决:

           包含jar包文件:

          image

    dom4j.jar和jaxen.jar

    创建、删除XML文件:XmlBuilder.java 文件

    package org.xml;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.SAXReader;
    import org.dom4j.io.XMLWriter;
    
    public class XmlBuilder {
    
        private String path; // XML保存和读取文件路径
        private Document doc; // XML文档对象
        private Element root; // XML文档根元素
    
        public XmlBuilder(String path) {
            this.path = path;
            doc = DocumentHelper.createDocument();
            root = null;
        }
    
        // 构造函数重载
        public XmlBuilder() {
            this.path = "";
            doc = DocumentHelper.createDocument();
            root = null;
        }
    
        // 返回XML文档对象
        public Document GetDoc() {
            return doc;
        }
    
        // 创建XML文件的根元素
        public Element CreateRoot(String name) {
            root = doc.addElement(name);
            return root;
        }
    
        // 返回XML文件根元素的名称
        public String GetRootName() {
            if (root != null) {
                return root.getName();
            }
            return null;
        }
    
        // 返回XML根元素
        public Element GetRoot() {
            return root;
        }
    
        // 设置XML文件保存或者访问的文件位置
        public void SetPath(String pathname) {
            this.path = pathname;
        }
    
        // 读取XML文件的private方法
        private Document readXML(String pathname) throws Exception {
            if (pathname != "") {
                SAXReader reader = new SAXReader();
                try {
                    this.SetPath(pathname);
                    doc = reader.read(new File(pathname));
                    root = doc.getRootElement(); // 读取XML文件,同时初始化root
                } catch (DocumentException e) {
                    throw new Exception("读取" + pathname + "XML文件出错!");
                }
                return doc;
            } else {
                throw new Exception("读取XML路径为空!");
            }
        }
    
        // 读取指定路径XML文件,返回Document对象
        public Document ReadXML(String xmlpath) throws Exception {
            this.path = xmlpath;
            return readXML(path);
        }
    
        // 读取已初始化路径的XML文件
        public Document ReadXML() throws Exception {
            return readXML(path);
        }
    
        // 保存XML文件的private方法
        private void saveXML(String savepath) throws Exception {
            if (savepath == "" || savepath == null) {
                throw new Exception("保存XML文件路径为空!");
            }
    
            if (doc != null) {
                try {
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter wrt = new XMLWriter(new FileOutputStream(new File(
                            savepath)), format);
                    wrt.write(doc);
                    wrt.close();
                } catch (IOException e) {
                    throw new Exception("保存" + savepath + "XML文件出错!");
                }
            } else {
                throw new Exception("Document 对象为空");
            }
        }
    
        // 使用自定义路径,保存XML文件
        public void SaveXML(String savepath) throws Exception {
            saveXML(savepath);
        }
    
        // 使用已初始化路径保存XML文件
        public void SaveXML() throws Exception {
            saveXML(path);
        }
    
        // XML文件输出到屏幕
        public void SaveConsole() throws Exception {
            if (doc != null) {
                try {
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter wrt = new XMLWriter(System.out, format);
                    wrt.write(doc);
                    wrt.close();
                } catch (IOException e) {
                    throw new Exception("XML输出至屏幕出错!");
                }
            } else {
                throw new Exception("Document 对象为空!");
            }
        }
    
    }

    XML文件增删查改操作:XmlOper.java

    package org.xml;
    
    import java.util.List;
    
    import org.dom4j.Attribute;
    import org.dom4j.Element;
    
    public class XmlOper extends XmlBuilder {
    
        public XmlOper() {
            super();
        }
    
        public XmlOper(String path) {
            super(path);
        }
    
        // 根据路径查询指定XML元素
        private List<?> QueryXMLByPath(String xpath) {
            List<?> list = this.GetDoc().selectNodes(xpath);
            return list;
        }
    
        // 根据名称查询Root下子元素,返回第一个匹配子元素
        private Element QueryXMLByName(String name) {
            Element elem = null;
            List<?> list = QueryXMLByPath("/" + this.GetRootName() + "/*");
            int len = list.size();
            for (int i = 0; i < len; i++) {
                Element sub = (Element) list.get(i);
                if (name.equals(sub.getName())) {
                    elem = sub;
                    break;
                }
            }
            return elem;
        }
    
        // 通过属性查询指定名称元素
        public Element QueryXML(String name, String attName, String attVal) {
            List<?> list = QueryXMLByPath("/" + this.GetRootName() + "/" + name);
            int len = list.size();
            Element elem = null;
            for (int i = 0; i < len; i++) {
                Element sub = (Element) list.get(i);
                Attribute att = HasAttribute(sub, attName);
                if (att != null && attVal.equals(att.getValue())) {
                    elem = sub;
                    break;
                }
            }
            return elem;
        }
    
        // 查询XML中指定名称的第一个匹配节点
        public Element QueryXML(String name) {
            if (name == this.GetRootName()) {
                return this.GetRoot();
            }
            return QueryXMLByName(name);
        }
    
        // 在指定元素下添加子元素
        public Element AddElement(Element elem, String name) {
            if (elem != null) {
                elem = elem.addElement(name);
            }
            return elem;
        }
    
        // 判断XML父元素中是否包含指定名称的子元素
        private Element HasElement(Element parent, String name) {
            Element has = null;
            List<?> list = parent.elements();
            for (int i = 0; i < list.size(); i++) {
                Element sub = (Element) list.get(i);
                if (name.equals(sub.getName())) {
                    has = sub;
                    break;
                }
            }
            return has;
        }
    
        // 判断XML元素中是否包含指定名称的属性
        private Attribute HasAttribute(Element elem, String attName) {
            Attribute has = null;
            List<?> list = elem.attributes();
            for (int i = 0; i < list.size(); i++) {
                Attribute att = (Attribute) list.get(i);
                if (attName.equals(att.getName())) {
                    has = att;
                    break;
                }
            }
            return has;
        }
    
        // XML指定元素中删除子元素
        public boolean RemoveElement(Element parent, String name) {
            boolean succ = false;
            if (parent != null && !parent.isTextOnly()) {
                Element sub = HasElement(parent, name);
                if (sub != null) {
                    succ = parent.remove(sub);
                }
            }
            return succ;
        }
    
        // XML指定元素下添加属性
        public Element AddAttribute(Element elem, String attName, String attVal) {
            if (elem != null) {
                elem.addAttribute(attName, attVal);
            }
            return elem;
        }
    
        // XML指定元素中删除指定属性
        public boolean RemoveAttribute(Element elem, String attName) {
            boolean succ = false;
            if (elem != null) {
                Attribute has = HasAttribute(elem, attName);
                if (has != null) {
                    succ = elem.remove(has);
                }
            }
            return succ;
        }
    
        // XML指定元素下添加值
        public Element AddText(Element elem, String text) throws Exception {
            if (elem != null) {
                if (!elem.isTextOnly()) {
                    throw new Exception("包含其他子元素,禁止添加文本!");
                }
                elem.addText(text);
            }
            return elem;
        }
    
        // XML指定元素下删除值
        public boolean RemoveText(Element elem) {
            boolean succ = false;
            if (elem != null && elem.isTextOnly()) {
                elem.setText("");
                succ = true;
            }
            return succ;
        }
    }
  • 相关阅读:
    22、栈的应用-中缀表达式转后缀表达式
    21、栈的应用-就近匹配
    20、双向链表
    19、链式栈
    Eclipse 重新加载插件
    Asp.net web form 使用IOC(Unity) 构造函数注入Page,.net Framework 4.7.2
    asp.net webform 多语言
    sql server 生成数字辅助表
    查询指定数据库的慢语句
    2008 sql 揭秘 第4章的数据库脚本
  • 原文地址:https://www.cnblogs.com/luosongchao/p/3433277.html
Copyright © 2020-2023  润新知