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,526 Responses

  1. ujlrsnnw表示:

    https://erythromycin1m.com/# erythromycin for sinus infection

  2. vtldlwzg表示:

    http://erythromycin1m.com/# what is the antibiotic erythromycin used to treat

  3. jenikla表示:

    Automated deletion
    If you are sure that your recipients are diligent, there is nothing to worry about – eLinkerMail lets you specify a date when the message should be deleted after being opened. This way you can be completely sure that the recipients have in fact read your message and that there is no risk that they will miss out on something important.

    References

    External links

    Category:Microsoft OfficeQ:

    how to add variable to a string https://distnetneydosohea.wixsite.com/inimapaj/post/memory-gauge-free-download-win-mac
    50e0806aeb jenikla

  4. bmumpaey表示:

    erythromycin benzoyl gel reviews erythromycin online

  5. Slonmob表示:

    3qfz3

    tsv2w

    0rqk

  6. channaun表示:

    Please see the below screenshots for how to use it:

    Installation

    The installation of the latest version, 0.1, is by downloading the latest JAR.
    Of course you can use zip file to extract it to your computer. In there you’ll get two JAR files.
    First JAR contains the Encryption program and the second one is the Encryption program’s main class file.
    Open Java Control Panel and go to the tab Security.
    Click on http://www.hjackets.com/?p=60591
    50e0806aeb channaun

  7. orsykla表示:

    “iSpace acts as your faithful assistant with a couple of essential functions,” Colin O’Briscol, the app’s developer said in a statement. “It can replace the 1, 2, 3, or 4 conventional double-spaces with a period and a space, and also provides a shortcut for users to capitalize the next word. Combined together, iSpace makes typing far more enjoyable.”

    iSpace is available as a free download on Google Play for Android devices and the https://lavivafashion.ie/wp-content/uploads/2022/06/saphivo.pdf
    50e0806aeb orsykla

  8. gerecol表示:

    Nonetheless, we encountered some rare compatibility issues with the Messaging Security Agent, which caused the client machine to slow down or freeze temporarily.

    Trend Micro Worry-Free Business Security combines all the best elements that a business should expect from a security product without having to splurge on a lot of modules and hard-to-install tools.

    There are many little tricks of programming and hiding some of the protocols and API’s that don’t seem to make sense unless you understand them. https://www.mycoportal.org/portal/checklists/checklist.php?clid=1576
    50e0806aeb gerecol

  9. jaspalbe表示:

    processor (The MINIMUM requirements of the program is 321 kb and 48 mb ram)
    · Office XP
    How to
    The main “Path” window contains several buttons, move right to find the application menu.
    Or you can also press the hotkeys (keyboard combination):
    alt+F: to open the program menu
    alt+E: to open start menu
    alt+S: to open desktop menu

    Compare the you nowYou have to select the programs and https://lear.orangeslash.com/advert/shoppingcart-store-app-crack-free-download/
    50e0806aeb jaspalbe

  10. bambguar表示:

    The created configurations are saved automatically.
    Additionally, the software can be used to provide a consistent display for all the clients connected to the same network. Thus, if you use a Super VGA without the need to configure each display, you only need to assign the monitors of the configuration to the system.
    It is absolutely free of charge and can be downloaded at

    Shop a fine selection of equipment for sport, business and home made https://tazzakhabar.com/2022/06/crystalblue-xp-theme-crack-3264bit/
    50e0806aeb bambguar

  11. innzeal表示:

    We suggest that you install the “Wallpaper Customizer” first, given that the latter helps the former to deliver the most user-friendly features.
    Enjoy Summer Beach Theme and experience it online as well as offline! You can find it on Cydia’s BigBoss repository for $2.99.Now available, the new Oberon can now join you in the fight, featuring Equilibrium’s highly acclaimed new game engine. Dynamax other select creatures to deliver flying attacks from the https://silkfromvietnam.com/fubbie-free-download-3264bit-updated-2022/
    50e0806aeb innzeal

  12. seligas表示:

    Getting around in the bright lights is made easy with the all new DAYCATS® Lighting Cube from Tyco Furniture. This traditional-style street lamp features a unique polar design that can be used indoors or out. DayCats lighting cubes are easy to use and give off a strong beam, supporting its 90-inch diameter.
    This lamp includes a 147 watt lamp, and is compatible with most DayCats (CCI-1519, E-150W, E- https://gimgame.ru/socialcalc-activation-code-download-mac-win/
    50e0806aeb seligas

  13. sambri表示:

    This is how it works: to produce the maximum effective usage, the program launches several instances working on different threads (usually, math equations are used) that consume an estimated average of 50% CPU load, which they keep until all threads are dead.
    Free version of Slow Down CPU
    To keep this service as effective and valuable as possible, it is now free. We can see that the developer has spared no effort in its development, which is why it is now available to the public at http://jasaborsumurjakarta.com/?p=1824
    50e0806aeb sambri

  14. gerwaki表示:

    What is new in this release:
    Correctly-positioned line markers
    Crimson Editor now includes line markers, meaning it is no longer necessary to specify their position.
    Correctly-positioned word markers
    Crimson Editor has enhanced its block highlighting feature to correctly highlight word markers.
    In the center of any cell (except macros), Crimson Editor highlights the starting and ending word markers, thus providing the user with a simple way to specify the ranges for regular search and replace http://listoo.de/wp-content/uploads/nartagg.pdf
    50e0806aeb gerwaki

  15. culhed表示:

    Drinks and Cocktails Cheat Sheet

    Cocktails

    Cocktails are alcoholic beverages with a mix of mixed ingredients. The most notable cocktail is the traditional martini. Cocktails are usually elaborated with a touch of rye or whiskey, a bit of bitters, a dash of maraschino, and an ice brick with a dash of vermouth on the other side.

    Most of the time, you will include ingredients to the recipes all in one go from https://bistrot-francais.com/blu-ray-tracker-patch-with-serial-key/
    50e0806aeb culhed

  16. zephalt表示:

    Smileys stick to your face and cheer up your new mood with a positive smiley animation, but also push it away by showing you a sad emoji.

    MDBio 9.9
    MDBio 9.9 is a powerful sequencer tool for Audio, Video and an fully featured audio application for editing audio. It is a merge of Djbio (song-seq) with TDM (time-date-message). Add your pictures to an audio mix/sequencer file https://pure-reef-24037.herokuapp.com/HDDStatus.pdf
    50e0806aeb zephalt

  17. dnhpjtjv表示:

    erythromycin medication erythromycin eye ointment for newborns

  18. hungabr表示:

    The app also has a few advanced features that most will not even use but makes for a great tool if you are looking for the best screen recording on Windows 10, so, if you haven’t given it a try yet, why not?
    It’s no secret that native online-stores often find it difficult to keep up with the ever-increasing number of mobile-ready eCommerce competitors that offer basic functionality, good content, and a mobile-first approach.
    Vocal https://elevatedhairconcepts.com/wp-content/uploads/2022/06/zeyhaid.pdf
    ec5d62056f hungabr

  19. nikyfoul表示:

    Gif To Icon Converter can convert from a variety of formats. Gif To Icon Converter is tested and verified for conversion from all of the following types of Gif files to ICO files in 3 easy steps.
    Gif To Icon Converter along with other software related to Gif and Gif to icons will make your Gif conversion experience much easier.
    If you are tired of converting your Gifs manually and using online GIF to icon converters, go with G https://pouss-mooc.fr/2022/06/04/3d-sexvilla-2-everlust-offline-crack-high-quality-rar-rar/
    ec5d62056f nikyfoul

  20. Slonmob表示:

    872yy

    gjg3y

    [url=http://novrazbb.com/#]ikfc[/url]

發佈留言

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