xmlreader.java

来自「一个MMORPG手机游戏的服务器端程序源代码」· Java 代码 · 共 75 行

JAVA
75
字号
package zsw_mmorpg.log;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;

public class XMLReader {
    String path;
    Document doc;
    public XMLReader(){
        
    }
    public XMLReader(String strPath) {//文件路径
        path = strPath;
        doc = initDocument(strPath);
    }

    public String getPath() {
        return path;
    }

    public void setPath(String strpath) {
        path = strpath;
    }

    public Document initDocument(String strPath) {
        try {
            if (doc == null) {
                DocumentBuilderFactory factory = DocumentBuilderFactory.
                                                 newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                doc = builder.parse(strPath);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return doc;
        }
    }
    public void setDocument(String xmlString){//xml文本字符串
        try{
        InputStream is = new StringBufferInputStream(xmlString);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(is);
        }
        catch(Exception e){
            
        }
    }
    public String getFirstTextByElementName(String elementName){//只得到第一个数据
        String tempStr="";
        NodeList nodeList = doc.getElementsByTagName(elementName);
        if(nodeList.getLength()>0)
            return nodeList.item(0).getChildNodes().item(0).getNodeValue();
        return tempStr;
    }
    public ArrayList getCollectionByElementName(String elementName){//只得到第一层的数据String[] firstLayerelementNames,
        ArrayList arrayList = new ArrayList();
        NodeList nodeList = doc.getElementsByTagName(elementName);//例如:得到名字为"UpSms"的元素列表
        for(int i =0;i<nodeList.getLength();i++){
            NodeList firstLayerNodeList = nodeList.item(i).getChildNodes();
            HashMap map = new HashMap();
            for(int j =0;j<firstLayerNodeList.getLength();j++){
                if(firstLayerNodeList.item(j).hasChildNodes() && firstLayerNodeList.item(j).getFirstChild().getNodeValue()!=null){
                    map.put(firstLayerNodeList.item(j).getNodeName(),firstLayerNodeList.item(j).getFirstChild().getNodeValue());
                }
            }
            arrayList.add(map);
        }
        return arrayList;
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?