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...

6,234 Responses

  1. Mazrffz表示:

    Добрый день!
    Как быстро получить диплом магистра? Легальные способы
    antiviruses.ru/about_antivirus/drwebdos

  2. Britney表示:

    Why Saab Key Replacement Cost Isn’t A Topic That People
    Are Interested In Saab Key Replacement Cost saab 93 replacement key (Britney)

  3. Rose表示:

    14 Savvy Ways To Spend On Leftover Anxiety Symptoms And Signs Budget signs and
    symptoms of anxiety disorder (Rose)

  4. Darrelherse表示:

    en iyi slot siteler: en iyi slot siteleri 2024 – slot siteleri

  5. Darrelherse表示:

    slot kumar siteleri: slot siteleri 2024 – casino slot siteleri

  6. 9 . What Your Parents Teach You About Infant Car
    Seats That Swivel Infant Car Seats That Swivel

  7. JesusLealt表示:

    deneme bonusu: bonus veren siteler – bonus veren siteler

  8. Sazrcsa表示:

    Привет!
    Диплом бакалавра
    telegra.ph/kupit-diplom-v-moskve-nedorogo-08-22-3

  9. Cazrkxe表示:

    Привет!
    Заказать диплом ВУЗа
    retro-lv.club/2020/08/nazvanija-ulic-v-rige

  10. Trefbtv表示:

    Привет!
    Процесс получения диплома стоматолога: реально ли это сделать быстро?
    wp1065308.server-he.de/doku.php?id=gosznacdiplom
    Будем рады вам помочь!.

  11. Suzette表示:

    3 Common Reasons Why Your Replacing Lost Car Keys Isn’t Working (And The Best Ways To
    Fix It) lost car key near me (Suzette)

  12. Lazrifg表示:

    Добрый день!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по невысоким тарифам.
    borisoglebsk.net/modules.php?name=Forums&file=viewtopic&p=28810

  13. Arjymm表示:

    oral celebrex 100mg – purchase indocin online cheap indomethacin 50mg cheap

  14. KevinSounc表示:

    http://slotsiteleri.bid/# en yeni slot siteleri

  15. KevinSounc表示:

    http://denemebonusuverensiteler.win/# deneme bonusu veren siteler

  16. Профессиональный сервисный центр по ремонту квадрокоптеров и радиоуправляемых дронов.
    Мы предлагаем:профессиональный ремонт квадрокоптеров
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  17. IT SHOULD BE ILLEGAL TO SELL HAIR FOR AS CHEAP AS WE ARE SELLING IT

  18. There’s noticeably a bundle to know about this. I assume you made sure nice factors in options also.

  19. Sazrcep表示:

    Привет, друзья!
    Купить документ института
    vossta.ru/

  20. Darrelherse表示:

    en cok kazandiran slot siteleri: bonus veren slot siteleri – en yeni slot siteleri

  21. Excellent article. I’m dealing with a few of these issues as well..

  22. Sazryiw表示:

    Добрый день!
    Мы изготавливаем дипломы любых профессий.
    Приобретение диплома, который подтверждает окончание ВУЗа, – это рациональное решение.
    newsinweek.ru/oformlenie-diplomov-s-minimalnyimi-zatratami
    Рады оказаться полезными!.

  23. Darrelherse表示:

    deneme bonusu veren slot siteleri: 2024 en iyi slot siteleri – slot bahis siteleri

  24. Mazruxz表示:

    Привет, друзья!
    Приобретение диплома ПТУ с сокращенной программой обучения в Москве
    hobby-svarka.ru/topic5021?&p=6427

  25. Comfortabl y, the post is really the freshest on this deserving topic. I harmonise with your conclusions and also can thirstily look forward to your next updates. Just saying thanks will not simply just be adequate, for the extraordinary clarity in your writing. I can directly grab your rss feed to stay informed of any updates. Gratifying work and much success in your business dealings!

  26. Some truly interesting information, well written and broadly speaking user pleasant.

  27. Stephenideox表示:

    Les avocats et conseillers financiers Fintech de RUE (Regulated United Europe) ont cree un blog ou ils publient les dernieres modifications de la legislation des pays europeens dans le domaine de la crypto-monnaie et du VASP (Virtual Asset Fournisseur de services) pour la commodite et l’information de tous ceux qui s’interessent a la legislation europeenne sur les crypto-monnaies. Nous basons nos articles sur des sujets importants pour les entrepreneurs d’aujourd’hui travaillant dans le domaine de la crypto-monnaie, des projets fintech, de la blockchain et des entreprises liees a l’informatique. Si vous ne trouvez pas les informations qui vous interessent sur notre blog, veuillez nous contacter de la maniere qui vous convient.

  28. Uazrifs表示:

    Добрыйдень!
    Приобрести диплом о высшем образовании.
    telegra.ph/gde-kupit-diplom-o-vysshem-obrazovanii-08-13-9

  29. GlennSaunk表示:

    It would seem that Maltese taxation is quite severe and the corporate income tax rate does not suggest that Malta is a low tax jurisdiction. However, this is not the case. The fact is that non-resident companies in Malta are entitled to a refund of taxes paid, which allows us to talk about the lower level of taxation in Malta compared to most countries in the world.
    In order to claim a corporate income tax refund, a foreign company must be registered in Malta as a trading or holding company (deriving its income from trading activities or from participation in other organisations, respectively).
    In the tax accounting of a Maltese company, the income earned by it must be recorded in one of four tax accounts: “foreign profits”, “Maltese profits”, “profits from immovable property”, “non-taxable income”. Each type of income is taxed according to its own rules. The final amount of tax is recorded in the fifth account “final tax”.
    Example. Consider the two most common cases: a Maltese company derives profits from trading activities abroad and from participation in other companies. In either case, these profits are subject to statutory tax at 35 per cent, but the Maltese shareholders are entitled to claim a refund of the tax taken from the dividends distributed. The refund rules differ for different types of income.
    If a Maltese company derives income from trading activities outside Malta (and the term “trading” includes both the direct purchase and sale of goods and the provision of services), its shareholders are entitled, upon receipt of the dividend, to apply for a refund of 6/7th of the tax previously paid in Malta. Therefore, the effective income tax rate will be 5 per cent.

  30. Dnrtnsp表示:

    Добрый день!
    Приобрести документ о получении высшего образования можно в нашем сервисе.
    wisdomtarot.tforums.org/viewtopic.php?f=8&t=3933

發佈留言

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