search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Home Backend Development XML/RSS Tutorial dom4j operates xml files (full)

dom4j operates xml files (full)

Feb 09, 2017 pm 02:14 PM
xml file

In the project, we use xml files a lot, whether it is parameter configuration or data interaction with other systems.
Today we will talk about using dom4j in Java to operate XML files.

The packages we need to introduce:

//文件包   
import java.io.ByteArrayOutputStream;   
import java.io.File;   
import java.io.FileWriter;   
//工具包   
import java.util.Iterator;   
import java.util.List;   
//dom4j包   
import org.dom4j.Attribute;   
import org.dom4j.Document;   
import org.dom4j.DocumentHelper;   
import org.dom4j.Element;   
import org.dom4j.io.OutputFormat;   
import org.dom4j.io.SAXReader;   
import org.dom4j.io.XMLWriter;

1. Convert the content of the XML file into String

  /** 
    * doc2String 
    * 将xml文档内容转为String 
    * @return 字符串 
    * @param document 
    */ 
   public static String doc2String(Document document) 
   { 
      String s = ""; 
      try 
      { 
           //使用输出流来进行转化 
           ByteArrayOutputStream out = new ByteArrayOutputStream(); 
           //使用GB2312编码 
           OutputFormat format = new OutputFormat("  ", true, "GB2312"); 
           XMLWriter writer = new XMLWriter(out, format); 
           writer.write(document); 
           s = out.toString("GB2312"); 
      }catch(Exception ex) 
      {             
           ex.printStackTrace(); 
      }       
      return s; 
   }

2. Convert the String that conforms to the XML format into XML Document

 /** 
    * string2Document 
    * 将字符串转为Document 
    * @return  
    * @param s xml格式的字符串 
    */ 
   public static Document string2Document(String s) 
   { 
      Document doc = null; 
      try 
      { 
           doc = DocumentHelper.parseText(s); 
      }catch(Exception ex) 
      {             
           ex.printStackTrace(); 
      } 
      return doc; 
   }

3. Save the Document object as an xml file locally

 /** 
    * doc2XmlFile 
    * 将Document对象保存为一个xml文件到本地 
    * @return true:保存成功  flase:失败 
    * @param filename 保存的文件名 
    * @param document 需要保存的document对象 
    */ 
   public static boolean doc2XmlFile(Document document,String filename) 
   { 
      boolean flag = true; 
      try 
      { 
            /* 将document中的内容写入文件中 */ 
            //默认为UTF-8格式,指定为"GB2312" 
            OutputFormat format = OutputFormat.createPrettyPrint(); 
            format.setEncoding("GB2312"); 
            XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format); 
            writer.write(document); 
            writer.close();             
        }catch(Exception ex) 
        { 
            flag = false; 
            ex.printStackTrace(); 
        } 
        return flag;       
   }

4. Save the string in xml format as a local file. If the string format does not comply with xml rules, failure will be returned

/** 
    * string2XmlFile 
    * 将xml格式的字符串保存为本地文件,如果字符串格式不符合xml规则,则返回失败 
    * @return true:保存成功  flase:失败 
    * @param filename 保存的文件名 
    * @param str 需要保存的字符串 
    */ 
   public static boolean string2XmlFile(String str,String filename) 
   { 
      boolean flag = true; 
      try 
      { 
         Document doc =  DocumentHelper.parseText(str);        
         flag = doc2XmlFile(doc,filename); 
      }catch (Exception ex) 
      { 
         flag = false; 
         ex.printStackTrace(); 
      } 
      return flag; 
   }

5. Load an xml document

 /** 
    * load 
    * 载入一个xml文档 
    * @return 成功返回Document对象,失败返回null 
    * @param uri 文件路径 
    */ 
   public static Document load(String filename) 
   { 
      Document document = null; 
      try  
      {  
          SAXReader saxReader = new SAXReader(); 
          document = saxReader.read(new File(filename)); 
      } 
      catch (Exception ex){ 
          ex.printStackTrace(); 
      }   
      return document; 
   }

6. Demonstrate saving a String as an xml file

 /** 
    * xmlWriteDemoByString 
    * 演示String保存为xml文件 
    */ 
   public void xmlWriteDemoByString() 
   { 
      String s = ""; 
      /** xml格式标题 "<?xml version='1.0' encoding='GB2312'?>" 可以不用写*/ 
      s = "<config>\r\n" 
         +"   <ftp name='DongDian'>\r\n" 
         +"     <ftp-host>127.0.0.1</ftp-host>\r\n" 
         +"     <ftp-port>21</ftp-port>\r\n" 
         +"     <ftp-user>cxl</ftp-user>\r\n" 
         +"     <ftp-pwd>longshine</ftp-pwd>\r\n" 
         +"     <!-- ftp最多尝试连接次数 -->\r\n" 
         +"     <ftp-try>50</ftp-try>\r\n" 
         +"     <!-- ftp尝试连接延迟时间 -->\r\n" 
         +"     <ftp-delay>10</ftp-delay>\r\n" 
         +"  </ftp>\r\n" 
         +"</config>\r\n"; 
      //将文件生成到classes文件夹所在的目录里    
      string2XmlFile(s,"xmlWriteDemoByString.xml");    
      //将文件生成到classes文件夹里    
      string2XmlFile(s,"classes/xmlWriteDemoByString.xml");   
   }

7. Demonstrate manually creating a Document and save it as an XML file

 /** 
    * 演示手动创建一个Document,并保存为XML文件 
    */ 
   public void xmlWriteDemoByDocument() 
   { 
        /** 建立document对象 */ 
        Document document = DocumentHelper.createDocument(); 
        /** 建立config根节点 */ 
        Element configElement = document.addElement("config"); 
        /** 建立ftp节点 */ 
        configElement.addComment("东电ftp配置"); 
        Element ftpElement = configElement.addElement("ftp"); 
        ftpElement.addAttribute("name","DongDian"); 
        /** ftp 属性配置 */ 
        Element hostElement = ftpElement.addElement("ftp-host"); 
        hostElement.setText("127.0.0.1"); 
        (ftpElement.addElement("ftp-port")).setText("21"); 
        (ftpElement.addElement("ftp-user")).setText("cxl"); 
        (ftpElement.addElement("ftp-pwd")).setText("longshine"); 
        ftpElement.addComment("ftp最多尝试连接次数"); 
        (ftpElement.addElement("ftp-try")).setText("50"); 
        ftpElement.addComment("ftp尝试连接延迟时间"); 
        (ftpElement.addElement("ftp-delay")).setText("10");     
        /** 保存Document */ 
        doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml"); 
   }

8. Demonstrate reading the value of a specific node in the file

  /** 
    *  演示读取文件的具体某个节点的值  
    */ 
   public static void xmlReadDemo() 
   { 
      Document doc = load("classes/xmlWriteDemoByDocument.xml"); 
      //Element root = doc.getRootElement(); 
      /** 先用xpath查找所有ftp节点 并输出它的name属性值*/ 
      List list = doc.selectNodes("/config/ftp" ); 
      Iterator it = list.iterator(); 
      while(it.hasNext()) 
      {    
          Element ftpElement = (Element)it.next(); 
          System.out.println("ftp_name="+ftpElement.attribute("name").getValue()); 
      } 
      /** 直接用属性path取得name值 */ 
      list = doc.selectNodes("/config/ftp/@name" ); 
      it = list.iterator(); 
      while(it.hasNext()) 
      {    
          Attribute attribute = (Attribute)it.next(); 
          System.out.println("@name="+attribute.getValue()); 
      } 
      /** 直接取得DongDian ftp的 ftp-host 的值 */ 
      list = doc.selectNodes("/config/ftp/ftp-host" ); 
      it = list.iterator(); 
      Element hostElement=(Element)it.next(); 
      System.out.println("DongDian's ftp_host="+hostElement.getText()); 
   }

9. Modify or delete a value or attribute

/** ftp节点删除ftp-host节点 */ 
ftpElement.remove(hostElement);  
/** ftp节点删除name属性 */ 
ftpElement.remove(nameAttribute); 
/** 修改ftp-host的值 */ 
hostElement.setText("192.168.0.1");  
/** 修改ftp节点name属性的值 */ 
nameAttribute.setValue("ChiFeng");


The above is the content of dom4j operating xml files (full). For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the XML Tools plugin in Notepad  ? (Plugin Manager) How to install the XML Tools plugin in Notepad ? (Plugin Manager) Mar 05, 2026 am 12:37 AM

Notepad v8.6.1 has completely removed the PluginManager. XMLTools cannot be installed because it has not been migrated to the new plug-in system and the author has stopped updating it. Manual installation is only applicable to v8.5.7 and earlier versions. It is recommended to use built-in functions or alternatives such as VSCode.

How to convert XML to YAML for DevOps? (Configuration Management) How to convert XML to YAML for DevOps? (Configuration Management) Mar 12, 2026 am 12:11 AM

xmltodict PyYAMListhesafestcomboforDevOpsconfigfilesbecauseitpreservescomments,CDATA,namespaces,andattributesaccurately,unlikerawXML-to-YAMLtoolsorCLIutilitieslikeyqandxmllintwhichsilentlydropcriticalmetadata.

How to format and beautify XML code in Notepad  ? (Pretty Print) How to format and beautify XML code in Notepad ? (Pretty Print) Mar 07, 2026 am 12:20 AM

Notepad needs to manually install and enable the XMLTools plug-in to format XML; if the tags are messed up or the content is lost after formatting, it means that the XML itself is illegal, and there are problems such as unclosed tags or illegal characters.

How to minify XML files for faster web loading? (Performance Optimization) How to minify XML files for faster web loading? (Performance Optimization) Mar 08, 2026 am 12:16 AM

RunningminifyonXMLwithoutunderstandingitsrulesbreaksparsingoralterssemanticsbecausewhitespacecanbemeaningful;safeminificationrequiresdata-orientedXML,controlledgeneration/consumption,andstrictparserawareness.

How to convert an XML file to a Word document? (Reporting) How to convert an XML file to a Word document? (Reporting) Mar 09, 2026 am 01:05 AM

python-docx does not support direct reading of XML files. You need to use xml.etree.ElementTree or lxml to parse the XML extraction fields first, and then write them into the Document object segment by segment. Explicit declaration of prefixes is required to process namespaces, and manual manipulation of the underlying XML is required for table merging and styling. Chinese paths should be avoided when saving.

How to use Attributes vs Elements in XML? (Design Best Practices) How to use Attributes vs Elements in XML? (Design Best Practices) Mar 16, 2026 am 12:26 AM

You should use attributes to store short metadata (such as id, type), and use elements to store scalable content data; because attributes do not support namespaces, duplication, nesting, and internationalization, their parsing is error-prone and maintenance is difficult.

How to parse XML data from a URL API? (Rest Services) How to parse XML data from a URL API? (Rest Services) Mar 13, 2026 am 12:06 AM

To parse remote XML API in Python, you need to use requests to get the response and then check the status code and Content-Type. Prioritize using r.text with xml.etree.ElementTree to parse; when encountering a namespace, you need to pass the namespace dictionary; use iterparse to stream large files and clear them manually; front-end JS requires CORS support or proxy.

How to open and view XML files in Windows 11? (Beginner Guide) How to open and view XML files in Windows 11? (Beginner Guide) Mar 12, 2026 am 01:02 AM

The XML file cannot be opened by double-clicking because it is associated with Notepad by default, causing confusion in the display. You should use Notepad, VSCode or Edge instead; Edge can format and report errors, while VSCode requires the installation of extensions such as RedHatXML for normal highlighting, indentation and verification.

Related articles