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

15,801 Responses

  1. MichaelBrift表示:

    Привет, если вы разыскиваете игровые автоматы, какие вправду дарят большие выигрыши, вы очутились как раз адресу! Мы подготовили ради тебя лучшие 5 игровых автоматов, какие за прошедший месяц сотворили родных игроков счастливее. Это все не просто слова — данные действительности, базирующиеся в существующей исчислении вознаграждений.

    Применяйте льготы и бесплатные вращения для испытания новых игровых автоматов.

    Попробуйте данные игровые автоматы на сайте Casino Flagman — а, вероятно, следующий большой приз станет твоим!

  2. Jasonzitte表示:

    Setting the benchmark for global pharmaceutical services.
    how to buy cheap benzac without a prescription
    They always offer alternatives and suggestions.

  3. sex nhật The Snapped Podcast, hiếp dâm trẻ em The Snapped Podcast, ấu dâm The Snapped Podcast

  4. child abuse表示:

    sex nhật hiếp dâm trẻ em ấu dâm buôn bán vũ khí ma túy bán súng sextoy chơi đĩ sex bạo lực sex học đường tội phạm tình dục chơi les đĩ đực người mẫu bán dâm

  5. Where Is Where To Get Pallets 1 Year From What Is Happening Now?
    Pallet prices

  6. WalterCherm表示:

    Consistently excellent, year after year.
    https://lisinoprilpharm24.top/
    The children’s section is well-stocked with quality products.

  7. Jacob表示:

    Ten Things Everyone Misunderstands About Electric Folding Lightweight Wheelchair
    best electric folding wheelchair (Jacob)

  8. Jasonzitte表示:

    They provide a global perspective on local health issues.
    can i get generic cytotec for sale
    I always find great deals in their monthly promotions.

  9. How A Weekly Twin Stroller Project Can Change Your Life double stroller For twins

  10. sex nhật The Snapped Podcast, hiếp dâm trẻ em The Snapped Podcast, ấu dâm The Snapped Podcast

  11. Eloy表示:

    How Dewalt Power Tool Set Transformed My Life For The Better power tools dewalt –
    Eloy,

  12. Victorprima表示:

    Trustworthy and reliable, every single visit.
    where to get cheap cipro pills
    A beacon of excellence in pharmaceutical care.

  13. WalterCherm表示:

    I always find great deals in their monthly promotions.
    https://cytotecpharm24.top/
    Every visit reaffirms why I choose this pharmacy.

  14. Victorprima表示:

    Quick, accurate, and dependable.
    cost of cheap clomid tablets
    Always a pleasant experience at this pharmacy.

  15. sex nhật hiếp dâm trẻ em ấu dâm buôn bán vũ khí ma túy bán súng sextoy chơi đĩ sex bạo lực sex học đường tội phạm tình dục chơi les đĩ đực người mẫu bán dâm

  16. jwnbfvlbo表示:

    You can find the best free slots games at US slots casinos. These casinos offer a wide selection of free slot games from top developers, so there are hundreds of free slots for you to explore. Free spin bonuses on most free online slots no download games are gotten by landing 3 or more scatter icons matching symbols. Some slot machines have up to 20 free spins that could be re-triggered by hitting more scatter symbols while others offer a flat extra spins number without re-trigger features. Gamers are not limited in titles when they have to play free slot machines. Below are popular free slots without downloading from popular developers such as Aristocrat, IGT, Konami, etc. In order to win tournaments playing Konami slots, you’ll need to make sure you place the maximum bet every time, press the button as fast as possible, and leave nothing to distractions. This is the best way to win tournaments whenever you play the Konami slots.
    https://photoclub.canadiangeographic.ca/profile/21525494
    2. Log in every day to collect daily bonuses, which can be redeemed for coins and spins. world series of poker free chips MICHELLE  |  CRUISE The best is about to get BETTER! Are you a big fan of online slot games and looking for House of Fun Free Coins? Look no further! House of Fun is an exciting casino game app featuring a variety of slot machines, captivating visuals, and thrilling gameplay. It’s available for download on both the App Store and Google Play Store, allowing players to easily access it on their mobile devices and enjoy endless entertainment. Which slots are the best? There are seven reels, described in full below. In the Grand National of 2023, but only in terms of what options are available and general times (e.g.. Level up with improved controls These coins function similarly to Gold Coins found on other platforms. You can purchase bundles of Coins, with prices starting at $4.99, or acquire free coins at ZitoBox by claiming bonuses, promo codes, giveaways, and other offers.

  17. Jasonzitte表示:

    Always a step ahead in international healthcare trends.
    can i order lisinopril without insurance
    Always up-to-date with international medical advancements.

  18. M.414500.Cc表示:

    The 10 Scariest Things About Specialized Containers Specialized Containers, M.414500.Cc,

  19. WalterCherm表示:

    They maintain a high standard of hygiene and cleanliness.
    https://cipropharm24.top/
    Their worldwide pharmacists’ consultations are invaluable.

  20. Jasonzitte表示:

    Always up-to-date with international medical advancements.
    cytotec buy
    A pharmacy that sets the gold standard.

發佈留言

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