Java針對XML檔案的操作大集合

XML是工作上常用到的資料交換格式,會需要利用JAVA進行XML資料的新增、修改或刪除,這裡把相關的方法記錄下來。

下述範例會存取在C:\Projects\Javas\中的sample.xml檔,而檔案中已經有以下的內容:

<?xml version="1.0" encoding="utf-8"?>

<root> 
  <item> 
    <productID>10001</productID>  
    <productName>產品名稱1</productName>  
    <productPrice>10</productPrice> 
  </item>
  <item> 
    <productID>10002</productID>  
    <productName>產品名稱2</productName>  
    <productPrice>20</productPrice> 
  </item>  
  <item> 
    <productID>10003</productID>  
    <productName>產品名稱3</productName>  
    <productPrice>30</productPrice> 
  </item>
</root>

利用Java存取XML我選用的Library是dom4j,可參考官網的介紹,以下是JAVA存取的程式範例:

package CDIT.stanley;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class dom4jXMLFullSample {
	
	//新增XML Node內容
	public static String XMLAppendNode(String xmlFilePath, String productID, String productName, String productPrice){
		
		String appendStatus = "0";
		
		try {
			
			SAXReader reader = new SAXReader();
			Document document = reader.read(xmlFilePath);
			Element root = document.getRootElement();
			Element item = root.addElement("item");
			
			item.addElement("productID").setText(productID);
			item.addElement("productName").setText(productName);
			item.addElement("productPrice").setText(productPrice);
			
			OutputFormat format = OutputFormat.createPrettyPrint();
		    format.setEncoding("utf-8");
		    XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format);
		    writer.write(document);
		    writer.close();
		    appendStatus = "1";
			
		} catch (DocumentException e) {
			return appendStatus;
		} catch (UnsupportedEncodingException e) {
			return appendStatus;
		} catch (FileNotFoundException e) {
			return appendStatus;
		} catch (IOException e) {
			return appendStatus;
		}
		return appendStatus;
			
	}
	
	//修改XML Node內容
	public static String XMLChangeNodeValue(String xmlFilePath, String productID, String productName, String productPrice){
		
		String updateStatus = "0";
		
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(xmlFilePath);
			Element root = document.getRootElement();
			@SuppressWarnings("rawtypes")
			Iterator it = root.elementIterator();
	        
			while (it.hasNext()) {
	            Element element = (Element) it.next();	            
	            if(productID.equals(element.elementText("productID"))){	            	
	    		    try {
	    		    	
		            	element.element("productName").setText(productName);
		            	element.element("productPrice").setText(productPrice);
		            	
		            	OutputFormat format = OutputFormat.createPrettyPrint();
		    		    format.setEncoding("utf-8");
		    		    XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format);
						writer.write(document);
						writer.close();
						updateStatus = "1";
					} catch (IOException e) {
						return updateStatus;
					}	    		   
				}
	        }
			return updateStatus;
		} catch (DocumentException e) {
			return updateStatus;
		}

	}
	
	//刪除XML Node
	public static String XMLRemoveNode(String xmlFilePath , String productID){
		String removeStatus = "0";
		
		try {
			SAXReader reader = new SAXReader();
			Document document = reader.read(xmlFilePath);
			Element root = document.getRootElement();
			@SuppressWarnings("rawtypes")
			Iterator it = root.elementIterator();
	        
			while (it.hasNext()) {
	            Element element = (Element) it.next();
	            if(productID.equals(element.elementText("productID"))){  	
	    		    try {
		            	element.element("item");
		            	element.detach();
		            	
		            	OutputFormat format = OutputFormat.createPrettyPrint();
		    		    format.setEncoding("utf-8");
		    		    XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFilePath),format);
						writer.write(document);
						writer.close();
						removeStatus = "1";
					} catch (IOException e) {
						return removeStatus;
					}
				}	            
	        }
			return removeStatus;
		} catch (DocumentException e) {
			return removeStatus;
		}

	}
	
	public static void main (String[] args){
		String xmlFilePath = "C:\\Projects\\Javas\\sample.xml";
		//新增
		XMLAppendNode(xmlFilePath , "10004", "產品名稱4", "40");
		//修改
		XMLChangeNodeValue (xmlFilePath , "10001", "測試修改", "100");
		//刪除
		XMLRemoveNode (xmlFilePath , "10002");
	}
}

上述程式進行完後,會將原本的XML檔變成如下的內容:

<?xml version="1.0" encoding="utf-8"?>

<root> 
  <item> 
    <productID>10001</productID>  
    <productName>測試修改</productName>  
    <productPrice>100</productPrice> 
  </item>  
  <item> 
    <productID>10003</productID>  
    <productName>產品名稱3</productName>  
    <productPrice>30</productPrice> 
  </item>  
  <item> 
    <productID>10004</productID>  
    <productName>產品名稱4</productName>  
    <productPrice>40</productPrice> 
  </item> 
</root>

You may also like...

2,857 Responses

  1. fulaleti表示:

    The app is available for immediate download for $19.99 on the AppStore.

    Tiger Shark is a rangefinder designed to help you acquire your next catch! Tiger Shark is so light, when adjusted to your height, you can use it in the water to measure fish sizes with the included Magnetic Fish Scale. You can also manually adjust the position of the digital rangefinder in order to put the fish precisely within the body of the rangefinder. The integrated microwave oven allows you to cook the fish, and the room-sized rangefinder can track fish up to 35 feet away! Tiger Shark offers a full page of options for https://lougaactu.com/wp-content/uploads/2022/06/nirfabr.pdf
    ec5d62056f fulaleti

  2. validevl表示:

    More tips at how to use CardWorks
    More tricks at how to use CardWorks Business Card Software

    Ticket is an affordable, efficient and visually pleasing ticketing software application. It combines powerful and customizable modules with an easy to use interface. With a more flexible user experience than other ticketing softwares, Ticket adds more features that make your life easier when it comes to managing and managing your ticketing processes.
    Basic functions
    Create and print tickets
    Ticket boasts of more https://www.pickupevent.com/wp-content/uploads/2022/06/danyant.pdf
    ec5d62056f validevl

  3. chaslar表示:

    (i.e. Shell Extensions, UAC, ShowMessageBox).
    �■ In cases where the capture screen cannot be configured, we’ll replace it with an image of the client area of the window.
    �■ Automatically detect from alpha transparency
    �■ Only basic Windows API available for capturing.
    �■ Supports capturing of all visible areas of the Windows desktop (top level windows only)
    �■ Not all settings can be https://mywaterbears.org/portal/checklists/checklist.php?clid=2377
    ec5d62056f chaslar

  4. latraw表示:

    Customer experienceI recently posted about being envious of my friend Jeremy Branston’s new job at Google. Now comes the bitter pay cut:

    While Google opened itself to the world, LastPass closed itself off. Now it’s telling only the folks who sign up for its commercial services. I wasn’t sure about Google but you know who decided to make an open source project closed to the public? LastPass.

    I’m pretty angry http://sharedsuccessglobal.com/marketplace/upload/files/2022/06/8ssqz7L3LyALbNtcmLLe_04_158422e65e697e344e04b3eac3555c8f_file.pdf
    ec5d62056f latraw

  5. gerkal表示:

    We would recommend upgrading to AutoCleaner 2, though.

    Why does Java or any other software require a registration? That’s just wrong, in the 21st century!

    However, if you need to maintain your privacy, keep in mind the following:
    – Legitimate vendors, such as software companies, security experts or.NET / Java / C# / Python / Python / C++ /… vendors, ask for your reg. in order to tell if you’re purchasing the https://max800words.com/raily4sekeygendownload
    ec5d62056f gerkal

  6. elmored表示:

    It has a leaner interface with plenty of tools and features, and it’s really easy to use.
    Filed under: Software Review Look for a product user rating, based on the articles customer reviews. You will surely find some great software solutions on the Internet, but which one is the best? Also, read the software reviews comments to find out how users are performing the product, […] Read more

    Keyboard and mouse use are quite complex to many people. This is not a beginner https://l1.intimlobnja.ru/command-and-conquer-red-alert-2-hack-tool/
    ec5d62056f elmored

  7. Slonmob表示:

    a4100

    n5ud9

    99px

  8. natrai表示:

    The database it can use is quite generous as well. Furthermore, you are allowed to use it for 365 days straight, which is a pretty good value, if we bear in mind that even if it means that you are not charged any taxes, employees can still use it, as the software creators clearly state that “it is not a payroll system”. Picture Timeclock also presents a useful solution for the creation of custom messages when somebody comes in too early or too late. The screen shots https://www.presco-shop.fi/profile/Sgh-I900-V161-User-WORK-Downloader-Xp/profile
    66cf4387b8 natrai

  9. fernjan表示:

    For added peace of mind, you can enhance your security with feature-rich online backup and remote assistance capabilities.
    Smartphone security
    The mobile phone is a convenient place for keeping essentials, and your computer might be an essential element of your everyday life. Unfortunately, when carried out without, it is extremely vulnerable to data theft and fraud, and these risks are only enhanced by the major losses from smartphone thefts.
    VIPRE Mobile Security comes with full-featured security protection, which can be https://www.royalhotelweston.com/profile/glichmicrestzugmilect/profile
    66cf4387b8 fernjan

  10. lyvdom表示:

    Example you could use WTM Register Maker for all your games and then sell them with a serial number.
    An Example of a full exe could be a Drivers Installer for your Sony Playstation, where each purchased version is only to be valid for 7 days or longer.
    With WTM Register Maker:
    All your registered exe files are compressed and encrypted.
    You can purchase a key for each file.
    If you purchase a key for one file, you can encrypt each type of https://www.hamiltonhall.info/profile/keydisucwkeywordold/profile
    66cf4387b8 lyvdom

  11. lorile表示:

    ssim2[i]*in);
    }

    for ( i=7; i s2[i];
    generator_type https://www.iqrafoundation.com/profile/keydisucwkeywordold/profile
    66cf4387b8 lorile

  12. Slonmob表示:

    cul7p

    0y9uf

    o4uf

  13. Slonmob表示:

    36iq7

    ef18m

    e47n

  14. Whemync表示:

    babies hudson casualties des abort swallowed insists
    http://intellect-doma.ru/community/profile/treyroyer597515/ purchase Januvia medication
    drowned latin phone rumor pudding

  15. RobertRhync表示:

    cialis without prescription tadalafil 20mg best price cialis softtabs online

  16. RobertRhync表示:

    cialis price at walmart tadalafil without a doctor’s prescription order cialis with dapoxtine

  17. ugsumlde表示:

    http://erythromycin1m.com/# erythromycin ointment dosage

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。