Java解析XML

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
云解析 DNS,旗舰版 1个月
简介:
由于需要对XML文件进行操作。所以上网找了一此资料。
用了一下org.w3c.dom解析,不太方便,特别是进行修改时。
后来找到了dom4j这个工具包。方便多了。呵。。记录一下,以后用得着。
首先通过org.w3c.dom解析
InitFromXML.java
package system.init;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author yymoth
*
*/
public class InitFromXML {
    private HashMap prop = new HashMap(); //存储从文件中读取的所有配置信息
    private HashMap temp = new HashMap(); //传入的参数,用来生成新的XML配置文件
    private static String xmlFileName ="SystemInit.xml";
    private static String xmlFilePath = InitFromXML.class.getClassLoader().getResource(xmlFileName).getPath();   
    private static InitFromXML instance = null;  
    public static synchronized InitFromXML getInstance()
    {
        if(instance == null)
        {    instance = new InitFromXML();    }
        
        return instance;
    }
    
    /**
     * 
     */
    public InitFromXML() {
        super();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new InitFromXML().getSystemProperty();
        
        HashMap temp = new HashMap();
        temp.put("outputImageDevice","outputImageDeviceVVVVV");
        temp.put("inputSceneFilePath","inputSceneFilePathVVVVV");
        temp.put("fetchIRADFactor",0.11);
        temp.put("fcpr_upLimit",111);     
        new InitFromXML().updateSystemProperty(temp);  
    }

    /**
     * 把xml文件读取内容,在内存中产生dom树; 修改它的内容不会影响文件;
     * @return
     */
    public HashMap getSystemProperty()
    {        
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        try {
            db = dbf.newDocumentBuilder();
            System.out.println("开始读取配置文件= " + xmlFilePath);
            Document d = db.parse(xmlFilePath);           
            NodeList nl = d.getElementsByTagName("outputImageDevice");
            Node mynode = nl.item(0);
            String outputImageDevice = mynode.getFirstChild().getNodeValue();
            prop.put("outputImageDevice",outputImageDevice);           
            System.out.println("输出路径= "+prop.get("outputImageDevice").toString());           
            nl = d.getElementsByTagName("inputSceneFilePath");
            mynode = nl.item(0);
            String inputSceneFilePath = mynode.getFirstChild().getNodeValue();
            prop.put("inputSceneFilePath",inputSceneFilePath);    
            System.out.println("输入场景路径= "+prop.get("inputSceneFilePath"));               
            nl = d.getElementsByTagName("fetchIRADFactor");
            mynode = nl.item(0);
            String fetchIRADFactor= mynode.getFirstChild().getNodeValue();
            prop.put("fetchIRADFactor",fetchIRADFactor);     
            System.out.println("空闲Render选择因子= "+prop.get("fetchIRADFactor"));          
            nl = d.getElementsByTagName("fcpr_upLimit");
            mynode = nl.item(0);
            int fcpr_upLimit = Integer.parseInt(mynode.getFirstChild().getNodeValue().toString().trim());
            prop.put("fcpr_upLimit",fcpr_upLimit);        
            System.out.println("单台Render最大渲染帧数= "+prop.get("fcpr_upLimit"));
            
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return this.prop;
    }
         
    /**
     * 更新系统参数
     *
     */
    public void updateSystemProperty(HashMap temp)
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        
        try {
            db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlFilePath);                     
            NodeList nl = doc.getElementsByTagName("outputImageDevice");
            Node mynode = nl.item(0);
            mynode.setTextContent((String)temp.get("outputImageDevice"));
            //mynode.setNodeValue((String)temp.get("outputImageDevice"));        
            nl = doc.getElementsByTagName("inputSceneFilePath");
            mynode = nl.item(0);
            mynode.setTextContent((String)temp.get("inputSceneFilePath"));  
            nl = doc.getElementsByTagName("fetchIRADFactor");
            mynode = nl.item(0);
            mynode.setTextContent((String)temp.get("fetchIRADFactor"));            
            nl = doc.getElementsByTagName("fcpr_upLimit");
            mynode = nl.item(0);
            mynode.setTextContent((String)temp.get("fcpr_upLimit")                   
            writeToXML(doc);           
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                            
    }
    
    
    /**
     * 把Document对象生成文件;
     * @param doc
     */
    
    public void writeToXML(Document doc)
    {
        TransformerFactory tfactory = TransformerFactory.newInstance();
        try {
            Transformer tf = tfactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(xmlFilePath));
            tf.transform(source,result);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

下面这个是通过DOM4J, 使用之前要下载dom4j包。官方站点:www.dom4j.org
Dom4j.java
package wcrs_master.test;
/**
* @author yymoth
*
*/
import java.io.IOException;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.SAXReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.Attribute;
import system.init.InitFromXML;
import java.io.FileWriter;
public class Dom4j {
    private static String xmlFileName ="SystemInit.xml";
    private static String xmlFilePath = Dom4j.class.getClassLoader().getResource(xmlFileName).getPath();
    private static Dom4j instance = null;
    public Dom4j() {
    }

    public static synchronized Dom4j getInstance()
    {
        if(instance == null)
        {    instance = new Dom4j();    }
        
        return instance;
    }
    public Document parse(String sfile) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(sfile));
        return document;
    }

    public void update(HashMap temp) throws IOException {
        Document document = null;
            try {
                document = new Dom4j().parse(xmlFilePath);
                Element root = document.getRootElement(); //得到根节点目录
                Iterator iter = root.elementIterator();
                System.out.println("\r\n****** 获取的数据如下 ******");
                System.out.println(xmlFilePath);
                while (iter.hasNext()) {
                    Element titleElement = (Element) iter.next();
                    // 修改xml元素
                    System.out.print(titleElement.getName()+"  ==  ");
                    System.out.println(titleElement.getData().toString());
                    
                    if (titleElement.getName().equals("outputImageDevice")) {
                        titleElement.setText(temp.get("outputImageDevice").toString());
                    }
                    if (titleElement.getName().equals("fetchIRADFactor")) {
                        titleElement.setText(temp.get("fetchIRADFactor").toString());
                    }
                    if (titleElement.getName().equals("inputSceneFilePath")) {
                        titleElement.setText(temp.get("inputSceneFilePath").toString());
                    }
                    if (titleElement.getName().equals("fcpr_upLimit")) {
                        titleElement.setText(temp.get("fcpr_upLimit").toString());
                    }
                }            
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            writeToXML(document);

    }

    /**
     * 把xml文件读取内容,在内存中产生dom树; 修改它的内容不会影响文件;
     * @return
     */
    public HashMap getSystemProperty()
    {
        HashMap temp = new HashMap();
        Document document ;
        try {
            document = new Dom4j().parse(xmlFilePath);
            Element root = document.getRootElement(); //得到根节点目录
            Iterator iter = root.elementIterator();
            while(iter.hasNext())
            {
                Element titleElement = (Element) iter.next();
                temp.put(titleElement.getName(),titleElement.getData());
            }
            
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return temp;
    }
    
    
    /**
     * 写入文件
     * @param document
     */
    
    public void writeToXML(Document document)
    {
        // 输出全部原始数据,在编译器中显示
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer;
        try {
            writer = new XMLWriter(System.out, format);
            //System.out.println("\r\n------------------Start------------------");
            writer.write(document);  
            //System.out.println("\r\n-------------------End-------------------");
            writer.close();
            // 输出全部原始数据,并用它生成新的我们需要的XML文件
            XMLWriter writer2 = new XMLWriter(new FileWriter(new File(
                    xmlFilePath)), format);
            writer2.write(document); //输出到文件
            writer2.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }      
        
    }         
    
    public static void main(String[] args) {
        
        HashMap temp = new HashMap();
        
        temp.put("outputImageDevice","outputImageDeviceVVVVV");
        temp.put("inputSceneFilePath","inputSceneFilePathVVVVV");
        temp.put("fetchIRADFactor",0.11);
        temp.put("fcpr_upLimit",11);
        
        Dom4j dom4j = new Dom4j();
        try {
            dom4j.update(temp);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

本文转自博客园执着的笨蛋的博客,原文链接:Java解析XML,如需转载请自行联系原博主。

目录
相关文章
|
3天前
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
16 2
|
7天前
|
Java
轻松上手Java字节码编辑:IDEA插件VisualClassBytes全方位解析
本插件VisualClassBytes可修改class字节码,包括class信息、字段信息、内部类,常量池和方法等。
52 6
|
5天前
|
存储 算法 Java
Java Set深度解析:为何它能成为“无重复”的代名词?
Java的集合框架中,Set接口以其“无重复”特性著称。本文解析了Set的实现原理,包括HashSet和TreeSet的不同数据结构和算法,以及如何通过示例代码实现最佳实践。选择合适的Set实现类和正确实现自定义对象的hashCode()和equals()方法是关键。
18 4
|
8天前
|
Java 编译器 数据库连接
Java中的异常处理机制深度解析####
本文深入探讨了Java编程语言中异常处理机制的核心原理、类型及其最佳实践,旨在帮助开发者更好地理解和应用这一关键特性。通过实例分析,揭示了try-catch-finally结构的重要性,以及如何利用自定义异常提升代码的健壮性和可读性。文章还讨论了异常处理在大型项目中的最佳实践,为提高软件质量提供指导。 ####
|
11天前
|
存储 Java 开发者
Java中的集合框架深入解析
【10月更文挑战第32天】本文旨在为读者揭开Java集合框架的神秘面纱,通过深入浅出的方式介绍其内部结构与运作机制。我们将从集合框架的设计哲学出发,探讨其如何影响我们的编程实践,并配以代码示例,展示如何在真实场景中应用这些知识。无论你是Java新手还是资深开发者,这篇文章都将为你提供新的视角和实用技巧。
12 0
|
6月前
|
XML JavaScript Java
详解Java解析XML的四种方法
详解Java解析XML的四种方法
338 1
|
XML Java 数据格式
java之DocumentBuilderFactory解析xml(2)
java之DocumentBuilderFactory解析xml(2)
267 0
|
XML JavaScript Java
java之DocumentBuilderFactory解析xml(1)
java之DocumentBuilderFactory解析xml(1)
420 0
|
XML Java 数据格式

推荐镜像

更多