xml檔案操作的java程式(續)

來源:互聯網
上載者:User
xml|程式 /**
     * helper方法,尋找一個指定的元素
     *
     * @param name 元素名稱,格式為 X.Y.Z
     * @return Element 如果找到就返回這個元素,否則返回null
     */
    public Element findOnly(String name)
    {
        //分解元素的名稱
        String[] propName = parsePropertyName(name);
        Element element = this.doc.getRootElement();
        //遍曆搜尋匹配的元素
        for (int i = 0; i < propName.length; i++)
        {
            element = element.getChild(propName[i]);
            if(element == null) return null;
        }
        //找到啦!
        return element;
    }
    /**
     * Saves the properties to disk as an XML document. A temporary file is
     * used during the writing process for maximum safety.
     */
    public synchronized void saveProperties() {
        OutputStream out = null;
        boolean error = false;
        // Write data out to a temporary file first.
        File tempFile = null;
        try {
            tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
            // Use JDOM's XMLOutputter to do the writing and formatting. The
            // file should always come out pretty-printed.
            //增加此行使得支援中文    wyl 20021015
            XMLOutputter outputter = new XMLOutputter("", true,"GB2312");
            out = new BufferedOutputStream(new FileOutputStream(tempFile));
            //增加此行,使得xml檔案沒有空行。 wyl 20021030
            outputter.setTextNormalize(true);
            outputter.output(doc, out);
        }
        catch (Exception e) {
            e.printStackTrace();
            // There were errors so abort replacing the old property file.
            error = true;
        }
        finally {
            try {  out.close();  }
            catch (Exception e) {
                e.printStackTrace();
                error = true;
            }
        }
        // No errors occured, so we should be safe in replacing the old
        if (!error) {
            // Delete the old file so we can replace it.
            if (!file.delete()) {
                System.err.println("Error deleting property file: " +
                        file.getAbsolutePath());
                return;
            }
            // Rename the temp file. The delete and rename won't be an
            // automic operation, but we should be pretty safe in general.
            // At the very least, the temp file should remain in some form.
            if (!tempFile.renameTo(file)) {
                System.err.println("Error renaming temp file from " +
                    tempFile.getAbsolutePath() + " to " + file.getAbsolutePath());
            }
        }
    }
   /**
     * Returns an array representation of the given crm property. crm
     * properties are always in the format "prop.name.is.this" which would be
     * represented as an array of four Strings.
     *
     * @param name the name of the crm property.
     * @return an array representation of the given crm property.
     */
    public String[] parsePropertyName(String name) {
        // Figure out the number of parts of the name (this becomes the size
        // of the resulting array).
        int size = 1;
        for (int i=0; i<name.length(); i++) {
            if (name.charAt(i) == '.') {
                size++;
            }
        }
        String[] propName = new String[size];
        // Use a StringTokenizer to tokenize the property name.
        StringTokenizer tokenizer = new StringTokenizer(name, ".");
        int i = 0;
        while (tokenizer.hasMoreTokens()) {
            propName[i] = tokenizer.nextToken();
            i++;
        }
        return propName;
    }
    private String[] parseAttributeName(String name)
    {
        // Figure out the number of parts of the name (this becomes the size
        // of the resulting array).
        if(name==null) return null;
        
        int size = 1;
        for (int i=0; i<name.length(); i++)
        {
            if (name.charAt(i) == '=')
            {
                size++;
            }
        }
        if(size!=2) return null;
        String[] attrName = new String[size];
        // Use a StringTokenizer to tokenize the property name.
        StringTokenizer tokenizer = new StringTokenizer(name, "=");
        for(int i=0;tokenizer.hasMoreTokens();i++)
            attrName[i] = tokenizer.nextToken();
        return attrName;
   }
    /**
    *    @param element element==null start from root
    *    @param attName attribute name
    *    @return attribute value of this element
    *    @author qiuss
    *    @date 2001.11.08
    */        
            
    public String getAttribute(Element element,String attName)
    {
        if(attName==null) return null;
        // Search for this property by traversing down the XML heirarchy.
        if(element==null) element = doc.getRootElement();
        Attribute att;
        String value;
        if((att=element.getAttribute(attName))!=null)
            value = att.getValue();
        else
            return null;
        if ("".equals(value))
        {
            return null;
        }
        else
        {
            return value.trim();
        }
    }     
    // qiuss 2001.11.08

    public String getAttribute(String eleName,String attName)
    {
        String[] propName = parsePropertyName(eleName);
        // Search for this property by traversing down the XML heirarchy.
        Element element = doc.getRootElement();
        for (int i = 0; i < propName.length; i++)
        {
            element = element.getChild(propName[i]);
            if (element == null)
            {
                    // This node doesn't match this part of the property name which
                    // indicates this property doesn't exist so return null.
                    return null;
            }
        }
        // At this point, we found a matching property, so return its value.
        // Empty strings are returned as null.
        String value ="";
        try{
            value= element.getAttribute(attName).getValue();
        }
        catch(Exception e)
        {
            value ="";
        }
        if ("".equals(value))
        {
            return "";
        }
        else
        {
            return value.trim();
        }
    }
    public static void main(String[] args)
    {
        XMLProperty xmltree = new XMLProperty("D:/project/bicp-ivr/crm_config.xml");
        //存在則更改元素的屬性值
        xmltree.setProperty("system.connection.username2","type","中文測試");
        //不存在則建立一個元素
        xmltree.setProperty("system.connection.使用者名稱稱","ecom4");
        xmltree.setProperty("system.connection.使用者名稱稱","type","中文測試2222");
        //刪除一個xml
//        xmltree.deleteProperty("system.connection.username2");
        String db_url= xmltree.getProperty("system.connection.db_url");
        String db_url_id="";
        db_url_id=xmltree.getAttribute("system.information.db_url","remark");
        Debug.println("db_url="+db_url);
        Debug.println("db_url_id="+db_url_id);
//        String names[] = xmltree.parsePropertyName("style.body");
//        for(int i=0;i<names.length;i++)
//        {
//            Debug.println("i="+i+" "+names[i]);
//        }
        String child[] = xmltree.getChildrenProperties("style.body");
        for(int j=0;j<child.length;j++)
        {
            Debug.println("j="+j+" "+child[j]);
            String child2[]= xmltree.getChildrenProperties("system.tracelog."+child[j]);
            for(int k=0;k<child2.length;k++)
            {
                Debug.println("k="+k+" "+child2[k]);
            }
        }

        //System.out.println("Hello World!");

    }
}

相關文章

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。