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

  1. Regards for this tremendous post, I am glad I noticed this site on yahoo.

  2. I have really learned new things from the blog post. One other thing to I have seen is that in most cases, FSBO sellers will certainly reject you actually. Remember, they’d prefer not to ever use your expert services. But if you actually maintain a gentle, professional partnership, offering guide and keeping contact for around four to five weeks, you will usually have the ability to win a conversation. From there, a house listing follows. Thanks a lot

  3. My spouse and i ended up being absolutely peaceful when Jordan managed to complete his studies from the ideas he made when using the blog. It’s not at all simplistic just to always be handing out procedures which often the rest might have been trying to sell. So we see we’ve got the writer to appreciate because of that. All of the explanations you’ve made, the easy site navigation, the friendships your site help foster – it’s all incredible, and it is leading our son in addition to the family feel that the situation is fun, and that is exceptionally indispensable. Thank you for the whole lot!

  4. Hi there, simply become aware of your blog thru Google, and found that it is truly informative. I’m gonna be careful for brussels. I will be grateful should you continue this in future. Lots of other folks can be benefited out of your writing. Cheers!

  5. Lazrcfk表示:

    Привет, друзья!
    Мы изготавливаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    forum.delta-dona.ru/profile.php?action=show&member=28708

  6. I used to be suggested this web site by my cousin. I am not positive whether or not this put up is written by him as no one else realize such detailed about my trouble. You’re amazing! Thanks!

  7. Hello I am so delighted I found your website, I really located you by mistake, while I was looking on google for something else, Anyways I am here now and could just like to say cheers for a tremendous post and a all round entertaining blog. Please do keep up the great work.

  8. great post, I enjoy it. I also buy ambien a lot. You need to buy ambien as well. I will travel to the whole USA and buy ambien there and in other areas to. i will be downtown, you know for what ? just to buy ambien. I will sleep a ton immediately after buy ambien and that it usually make me feel so very good. I will be buy ambien in a pharmacy or a different locations, no matter what the existence consider me .

  9. I am often to blogging i genuinely appreciate your posts. The content has truly peaks my interest. I’m going to bookmark your internet site and keep checking for brand new info.

  10. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи услуги

  11. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи екб

  12. the most common table lamp these days still use incandescent lamp but some of them use compact fluorescent lamps which are cool to touch*

  13. Scottdiz表示:

    1вин официальный сайт: ван вин – 1win зеркало

  14. Scottdiz表示:

    vavada online casino: вавада казино – казино вавада

  15. Sazrqnn表示:

    Приобретение школьного аттестата с официальным упрощенным обучением в Москве

    thehubbcommunitynetwork.mn.co/posts/65294191

  16. Если вы искали где отремонтировать сломаную технику, обратите внимание – сервисный центр в екб

  17. I am curious to find out what blog system you have been using? I’m experiencing some minor security problems with my latest site and I would like to find something more secure. Do you have any recommendations?

  18. An impressive share, I simply given this onto a colleague who was simply doing a small analysis about this. And then he in reality bought me breakfast since I ran across it for him.. smile. So i want to reword that: Thnx for the treat! But yeah Thnkx for spending plenty of time to discuss this, I find myself strongly regarding it and love reading regarding this topic. If you can, as you become expertise, might you mind updating your website with increased details? It can be highly ideal for me. Huge thumb up with this text!

  19. Scottdaurf表示:

    pin up casino: пин ап казино вход – пин ап казино

  20. Scottdaurf表示:

    пин ап зеркало: пинап казино – пин ап вход

  21. JamesNut表示:

    Have the Charges Against Vasilenko for Fraud Been Dropped?
    Бест Вей
    According to various sources, the criminal prosecution of Roman Vasilenko, the founder of the marketing company “Life-is-Good” and the cooperative “Best Way,” may be discontinued. Law enforcement agencies, as informed by several senators and State Duma deputies, have re-evaluated the charges against him, taking into account that several witnesses, including those critical of Vasilenko, suggest that he is unlikely to be involved in fraud. This is primarily because he did not have direct access to the payment system servers, and it was the former IT director of “Life-is-Good,” Evgeny Naboychenko, who had been previously implicated in fraudulent activities. Vasilenko may be at fault only for having recruited Naboychenko in 2014, despite negative signals regarding his behavior and tendencies to appropriate others’ property.

    Roman Viktorovich Vasilenko is a business consultant from Saint Petersburg, the creator of a network of independent entrepreneurs promoting financial products under the auspices of the company he founded, “Life-is-Good,” and the founder of the International Business Academy (IBA).

    The network under the “Life-is-Good” brand promoted financial products such as Vista accounts for passive income by the foreign investment company “Hermes,” registered in Belize, and the acquisition of apartments in installments through the “Best Way” cooperative, which allowed members to either make an initial share payment or accumulate it in the cooperative’s account without interest. Notably, these legal entities are not directly connected.

    Vasilenko was neither a top manager nor an owner of “Hermes”—he cooperated with the company to promote its products in Russia. However, Naboychenko was an employee of “Hermes” and managed its payment system in Russia. He likely took this position on Vasilenko’s recommendation, but Vasilenko was not responsible for managing the payment system for “Hermes.”

    Unlike “Hermes,” Vasilenko was the founder and chairman of the board of the “Best Way” cooperative until the spring of 2021 (later serving as head of the supervisory board for about a year). Since spring 2022, he has been an ordinary member of the cooperative and is no longer part of its governing bodies.

    Vasilenko has worked not only in Russia but also in Kazakhstan, Kyrgyzstan, Belarus, Ukraine, Cyprus, Austria, and Hungary. Cooperative housing projects have been established in many of these countries.

    Additionally, Vasilenko is known as a philanthropist who has invested millions of rubles in supporting federal business initiatives (such as the “Synergy” forum), cultural initiatives (such as the “Dobrovidenie” festival), and other charitable activities (including support for children’s medical institutions).

    The Case

    The criminal case involving the Saint Petersburg marketing company “Life-is-Good,” the foreign investment company “Hermes,” and the “Best Way” cooperative registered in Saint Petersburg and operating throughout Russia was initiated in the fall of 2021 by the Main Investigation Department of the Ministry of Internal Affairs of Russia for Saint Petersburg and the Leningrad Region. In February of this year, the case was referred to the court and is currently being heard in the Primorsky District Court of Saint Petersburg.

    Ten people are on trial, including technical staff from “Life-is-Good” and Victor Vasilenko, Roman Vasilenko’s 83-year-old father, who is a retiree.

    The criminal case, currently being considered by the Primorsky District Court, raises many questions—these concerns existed from the beginning and have intensified as the case progressed. The defendants are charged with three articles: creating a financial pyramid, fraud, and organizing a criminal community.

    The total amount of damage is 282 million rubles, which is incomparable to the more than 8 billion rubles seized in the case, including 4 billion rubles in the accounts of the “Best Way” cooperative. The investigation has recognized 221 citizens as victims in the case.

    Roman Vasilenko was also charged in the criminal case being considered by the court and was put on the wanted list, including by Interpol, as he had reportedly been living abroad for family reasons since the COVID-19 pandemic. However, according to sources, Interpol and foreign states, including neighboring countries where he has been actively working, deemed his prosecution unjustified.

    Another criminal investigation related to Vasilenko, handled by the Saint Petersburg Main Directorate of the Ministry of Internal Affairs, concerns the management team of “Life-is-Good.”

    Questionable Accusations

    The court proceedings in the Primorsky District Court have so far not been very successful for the investigation and the prosecution: the vast majority of those who have testified in court so far have made claims against “Hermes” for amounts ranging from several hundred to several tens of thousands of rubles, which raises eyebrows—this is not a small claims court to discuss such sums! Prosecution witness Roman Roganovich, an IT service employee, testified that he did not post any illegal information on the “Life-is-Good” website or the cooperative’s website and did not witness any illegal activity.

    Moreover, the overwhelming majority of “Hermes” clients, numbering over two hundred thousand in Russia, and tens of thousands of “Best Way” cooperative members, according to representatives of organizations defending these entities, consider law enforcement agencies to be the source of their problems. They emphasize that it was Evgeny Naboychenko, the Saint Petersburg system administrator hired by “Hermes,” who dismantled the Russian payment system. And if anyone is responsible for the thefts, it is Naboychenko. It seems that law enforcement authorities are beginning to understand this fact as well.

  22. Greetings! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  23. Профессиональный сервисный центр по ремонту радиоуправляемых устройства – квадрокоптеры, дроны, беспилостники в том числе Apple iPad.
    Мы предлагаем: ремонт дрона
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  24. Профессиональный сервисный центр по ремонту радиоуправляемых устройства – квадрокоптеры, дроны, беспилостники в том числе Apple iPad.
    Мы предлагаем: ремонт квадрокоптеров в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  25. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи тех сервис спб

  26. Если вы искали где отремонтировать сломаную технику, обратите внимание – профи ремонт

發佈留言

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