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

7,741 Responses

  1. Here’s A Little Known Fact Regarding Adhd Adult
    Assessment adhd assessments For adults near me

  2. Double Glaze表示:

    What Is The Reason Double Glazing Repairs Near Me Is Right For You
    Double Glaze

  3. The Most Negative Advice We’ve Ever Received On 18 Wheeler Wreck Lawyers 18 Wheeler Accident

  4. berita aceh表示:

    Hello there, I do think your web site could possibly be having web browser compatibility problems. Whenever I look at your site in Safari, it looks fine but when opening in I.E., it has some overlapping issues. I simply wanted to give you a quick heads up! Besides that, fantastic blog!

  5. 13 Things About Double Glazed Windows High Wycombe You May Never Have Known Upvc windows High wycombe

  6. Fela Lawyers表示:

    The Comprehensive Guide To Fela Accident Attorney Fela Lawyers

  7. Norma表示:

    9 Things Your Parents Taught You About Upvc Window Repairs upvc window
    repairs near me – Norma,

  8. FobertWen表示:

    I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get got an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this hike.
    gama casino официальный сайт

  9. The Best Place To Research Door Fitter Bedford Online windows fittings bedfordshire (http://www.Blackseo.com)

  10. porn video表示:

    This is a topic that is near to my heart… Best wishes! Where are your contact details though?

  11. 15 Secretly Funny People Working In Auto Key Locksmith Near Me
    Automotive Lock Smith Near Me

  12. You’ll Never Be Able To Figure Out This 18 Wheeler Accident
    Law Firm’s Secrets 18 wheeler accident law firm

  13. Adrianjug表示:

    KMSpico Download | Official KMS Website New July 2024
    office toolkit скачать
    Are you looking for the best tool to activate your Windows & Office? Then you should download and install KMSpico, as it is one of the best tools everyone should have. In this article, I will tell you everything about this fantastic tool, even though I will also tell you if this is safe to use.

    In this case, don’t forget to read this article until the end, so you don’t miss any critical information. This guide is for both beginners and experts as I came up with some of the rumours spreading throughout the internet.

    Perhaps before we move towards downloading or installing a section, we must first understand this tool. You should check out the guide below on this tool and how it works; if you already know about it, you can move to another section.
    What is KMSPico?
    KMPico is a tool that is used to activate or get a license for Microsft Windows as well as for MS Office. It was developed by one of the most famous developers named, Team Daz. However, it is entirely free to use. There is no need to purchase it or spend money downloading it. This works on the principle of Microsft’s feature named Key Management Server, a.k.a KMS (KMSPico named derived from it).

    The feature is used for vast companies with many machines in their place. In this way, it is hard to buy a Windows License for each device,, which is why KMS introduced. Now a company has to buy a KMS server for them and use it when they can get a license for all their machines.

    However, this tool also works on it, and similarly, it creates a server on your machine and makes it look like a part of that server. One thing different is that this tool only keeps the product activated for 180 days. This is why it keeps running on your machine, renews the license keys after 180 days, and makes it a permanent activation.

    KMSAuto Net
    Microsoft Toolkit
    Windows Loader
    Windows 10 Activator
    Features
    We already know what this tool means, so let’s talk about some of the features you are getting along with KMSPico. Reading this will surely help you understand whether you are downloading the correct file.

    Ok, so here are some of the features that KMSPico provides:

    Activate Windows & Office

    We have already talked about this earlier, as using this tool, you will get the installation key for both Microsoft Products. Whether it is Windows or Office, you can get a license in no time; however, this supports various versions.

    Supports Multi-Arch

    Since this supports both products, it doesn’t mean you have to download separate versions for each arch. One version is enough, and you can get the license for both x32-bit or even the x64-bit.

    It Is Free To Use

    Undoubtedly, everything developed by Team Daz costs nothing to us. Similarly, using this tool won’t cost you either, as it is entirely free. Other than this, it doesn’t come with any ads, so using it won’t be any trouble.

    Permanent License

    Due to the KMS server, this tool installs on our PC, we will get the license key for the rest of our lives. This is because the license automatically renews after a few days. To keep it permanent, you must connect your machine to the internet once 180 days.

    Virus Free

    Now comes the main feature of this tool that makes it famous among others. KMSPico is 100% pure and clean from such viruses or trojans. The Virus Total scans it before uploading to ensure it doesn’t harm our visitors.

  14. Douglasslida表示:

    KMSpico: What is it?
    kmspico rsload
    Operating systems and Office suites are among the primary Microsoft software items that still need to be paid for. Some consumers may find alternate activation methods due to the perceived expensive cost of these items. There may be restrictions, unforeseen interruptions, and persistent activation prompts if these items are installed without being properly activated.

    Our KMSpico app was created as a solution to this issue. By using this program, customers may access all of the functionality of Microsoft products and simplify the activation procedure.
    KMSPico is a universal activator designed to optimize the process of generating and registering license codes for Windows and Office. Functionally, it is similar to key generators, but with the additional possibility of automatic integration of codes directly into the system. It is worth paying attention to the versatility of the tool, which distinguishes it from similar activators.
    The above discussion primarily focused on the core KMS activator, the Pico app. Understanding what the program is, we can briefly mention KMSAuto, a tool with a simpler interface.

    By using the KMSPico tool, you can setup Windows&Office for lifetime activation. This is an essential tool for anybody looking to reveal improved features and go beyond limitations. Although it is possible to buy a Windows or Office key.

    KMSPico 11 (last update 2024) allows you to activate Windows 11/10/8 (8.1)/7 and Office 2021/2019/2016/2013/2010 for FREE.

  15. 10 Things That Your Family Teach You About Best Capsule Coffee Machine best capsule
    coffee machine; https://Comunidadeqm.Marcelodoi.Com.br/,

  16. This Week’s Most Remarkable Stories About Upvc Window Repairs Upvc Window Repairs window repairs near me

  17. Howdy! I could have sworn I’ve been to this blog before but after looking at a few of the articles I realized it’s new to me. Anyways, I’m certainly pleased I discovered it and I’ll be book-marking it and checking back often.

  18. Lnzkxg表示:

    flexeril 15mg price – enalapril 10mg ca order vasotec 10mg

  19. This Is How Window Repair Near Will Look Like In 10 Years
    Time window Repairs – https://emdrive.echothis.com,

  20. Why You Should Concentrate On Making Improvements To Crawley Door Panels
    front door repairs near me

  21. 10 Mobile Apps That Are The Best For Mesothelioma Case Mesothelioma attorneys

  22. 15 Bizarre Hobbies That’ll Make You More Successful At Psychiatry Assessment Uk psychiatric Diagnostic assessment

  23. Mesothelioma Law Firm Tips From The Top In The Industry leading mesothelioma lawyer

  24. uk表示:

    20 Things You Must Know About Window And Door Replacement London uk

  25. A Guide To Car Accident Lawyer In 2023 car accident law Firms [Mail.jkmulti.vip]

  26. tubidy music表示:

    You ought to take part in a contest for one of the most useful websites on the net. I will highly recommend this site!

發佈留言

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