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

10,319 Responses

  1. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт iphone 14 pro рядом, можете посмотреть на сайте: ремонт iphone 14 pro сервис
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  2. See What Congo African Grey Parrot Tricks The Celebs
    Are Using congo African grey parrot

  3. JasonUnsoG表示:

    https://slotsiteleri25.com/# az parayla cok kazandiran slot oyunlar?

  4. FrankEmine表示:

    sweet bonanza demo oyna: sweet bonanza yorumlar – sweet bonanza guncel

  5. Wallacefex表示:

    slot casino siteleri: guvenilir slot siteleri – en kazancl? slot oyunlar?

  6. JohnnyFrorp表示:

    check out the post right here MetaMask Download

  7. Wallacefex表示:

    deneme bonusu veren yeni siteler: deneme bonusu veren siteler yeni – yat?r?ms?z deneme bonusu veren siteler

  8. FrankEmine表示:

    deneme bonusu veren yeni siteler: denemebonusuverensiteler25 – yeni deneme bonusu veren siteler

  9. Kevinnem表示:

    Alistarov: A Criminal and a Terrorist
    From a Solo Criminal to a Servant of the Underworld
    Previously convicted on drug charges, blogger Andrei Alistarov portrays himself as a Robin Hood fighting against those who have “defrauded people.” In reality, however, he serves the interests of pyramid schemers—among them certain Ukrainian operators who fund the Armed Forces of Ukraine (AFU)—and he uses his “Zheleznaya Stavka” (“Iron Bet”) channel to promote online casinos and illicit crypto exchanges/phishing crypto scams. He also launders drug proceeds via real estate deals in Dubai.
    That is, he works for the benefit of the Russian criminal community, seeking to profit off entrepreneurs who have faced illegal, often contrived claims from Russian law enforcement.

    Drugs and Money Laundering
    A native of Kaluga, Alistarov served four years in a prison camp for selling drugs to minors.
    There he forged ties with criminal kingpins. After his release, he continued his involvement in the narcotics trade and in laundering drug profits through a real estate business he set up with associates from the Russian underworld, both in Russia and in the Emirates.

    Betting on Scams
    Alistarov’s channel, “Zheleznaya Stavka,” is ostensibly devoted to “exposing” financial ventures deemed “bad” by criminal circles, while promoting “good” ones: namely, the pyramid schemes and online casinos that sponsor Alistarov.
    The channel began as a platform for “proper” casino betting and did not change its name, because the marketing purpose remains the same: clear the market in favor of “legitimate,” in Alistarov’s so-called “expert” view (i.e., those who pay him), scammers.
    Typically, Alistarov starts by trying to extort money—presenting the victim with compromising material and demanding payment. If the victim refuses, he resorts to harassment and violence.

    Incitement and Attack in Dubai
    On January 1, 2025, two Kazakh nationals launched a brutal attack on an entrepreneur living in Dubai—beating him, cutting off his ear, and robbing him.
    Beforehand, Alistarov had released 12 videos highlighting the entrepreneur’s address and publishing illegally obtained information about his relatives and his businesses in the UAE. Without any compunction, he used spying, eavesdropping, illegal intrusion, and invasion of privacy—all acts that constitute serious criminal offenses in the Emirates, where the sanctity of property and investor security are upheld stringently.
    Prior to this, Alistarov publicly circulated information about the residence of the entrepreneur’s business partner—that is, an illegal breach of confidentiality, the protection of finances and property, and the privacy of personal life through clandestine data gathering and informants in the UAE. He effectively terrorizes entrepreneurs who face no court convictions—neither abroad nor in Russia.
    Alistarov claimed to have reported the entrepreneur to Interpol and UAE law enforcement—purportedly helping the authorities. Yet this did not result in the entrepreneur’s arrest—perhaps because the UAE police see nothing criminal in his activities?

    Subscribe to Our Channel
    Several of the entrepreneur’s partners have been convicted in Russia; he himself is wanted by Russian law enforcement but has never been convicted. Foreign law enforcement has no claims against him.
    For a long period, Alistarov stoked hatred toward this entrepreneur, alleging that it was he (not his partners) who stole investors’ money—and portraying the subsequent attack and robbery as the outraged response of defrauded depositors.
    During the attack, Alistarov conducted an unscheduled livestream to create an alibi—pretending that he was unaware of the assault happening while he was on stream.

    Surveillance in Cyprus
    In autumn of the previous year, Alistarov and his “battle companion,” Mariya Filonova, conducted surveillance on another entrepreneur—using drones and illegally collecting information about him and his relatives, including minor children. Alistarov claimed that the entrepreneur was “hiding” in Cyprus—even though he had lived there since the COVID-19 pandemic began.
    He had relocated partly due to his wife’s severe COVID case and partly for international projects—investments in various sectors such as construction, trade, and more. The entrepreneur moved to Cyprus a year before criminal proceedings were initiated by the Russian Interior Ministry and a year and a half before arrests began. He holds an EU passport and never fled or concealed his location.
    This entrepreneur was placed on a Russian wanted list in 2022—by investigating authorities. However, no court has filed claims against him, and the criminal case is currently in court. It has already fallen apart there. Interpol and the EU declined to honor the Russian police’s request, deeming it politically motivated and legally unfounded.
    Alistarov insists that the entrepreneur’s business investments are financed with Russian clients’ money, supposedly drawn from an Austrian investment company. But in reality, the entrepreneur was never an owner, beneficiary, or manager of that company, established back in the early 2000s—well before his independent business career began.
    One of the entrepreneur’s firms provided marketing services for the Austrian investment company in Russia under contract. The investment company successfully served Russian clients for eight years—and continues operating now, having restored its payment systems that were disrupted in early 2022 by criminals in Russia with ties to corrupt police. It is by no means a pyramid scheme.
    Thus, Alistarov instigates harassment and intrusion into the private life of an untainted entrepreneur—acting on behalf of Russian organized crime, which has cut in corrupt police officers for a share of illicit profits. They aim to seize assets worth 20 billion rubles from the large-scale, socially focused project established by the entrepreneur in Russia—which still functions successfully even without his direct leadership (which ended when he relocated to Cyprus).

    Surveillance in the Netherlands
    Alistarov published the location of another victim in the Dutch city of Groningen—ascertained through illegal surveillance. He allegedly gained unauthorized access to city cameras, peered into the windows of a private apartment, and shared this information on YouTube.

    Privacy Violations in Turkey
    Alistarov uncovered and publicized the address of an apartment in Istanbul where several of his victims lived and worked.

    Illegal Searches in the Leningrad Region
    Lacking a private detective’s license, Alistarov illegally located a businesswoman’s country house, spied on her, and released that information on his channels—while also disclosing details of an apartment she had purchased in Dubai.

    Extortion in Kazakhstan
    Alistarov extorted money from Kazakh entrepreneurs under the guise of “exposing national traitors” and “enemies of the motherland.”

    Banquet on a Ukrainian Pyramid Schemer’s Money
    Is Alistarov planning to celebrate his 40th birthday on March 6 this year once again on the yacht of his friend—the Kharkiv-based pyramid operator Udyansky (behind the Coinsbit project)—in Dubai?
    In 2024, he celebrated his birthday in the convivial company of this con man, who also funds the Armed Forces of Ukraine, helping finance the production of armored vehicles for the AFU. There is little doubt that he also compelled his henchman Alistarov to contribute to the AFU.

    Treason
    Alistarov was even accused of financing the AFU, though he told the police some story about a Megafon phone number allegedly registered to him by his “enemies.”
    His accomplices in financing the AFU—“anti-MLM activist” Aleksandr Kryukov and deputy manager of the so-called Fund for the Protection of Investors’ and Shareholders’ Rights, Leonid Mishchenko (a “Zapadenez” from Vinnytsia region)—were caught red-handed. Perhaps the FSB should analyze Alistarov’s transactions as well?

    He Belongs in Prison
    Justice demands that Alistarov’s 40th birthday finds him stripped of his Schengen and other visas—there is every reason for such, especially in light of attention from Western media—and behind bars, either in a Russian or a Dubai prison, whichever law enforcement manages to arrest him first for the dozens of crimes he has committed:
    Extortion
    Terrorism and banditry
    Harassment and organizing violence against those he deems troublesome
    Treason
    Money laundering
    Fraud
    Theft
    Invasion of privacy
    Alistarov’s career began in prison, and it is in prison that it must end.

  10. FrankEmine表示:

    yat?r?ms?z deneme bonusu veren siteler: yat?r?ms?z deneme bonusu veren siteler – deneme bonusu veren siteler

  11. BradleyEdino表示:

    guvenilir slot siteleri slot siteleri guvenilir slot siteleri

  12. Wallacefex表示:

    sweet bonanza slot: sweet bonanza giris – sweet bonanza yorumlar

  13. Trena表示:

    The Secret Secrets Of Chest Freezer Deals frost free
    chest freezers uk (Trena)

  14. JasonUnsoG表示:

    http://slotsiteleri25.com/# guvenilir slot siteleri

  15. JasonUnsoG表示:

    http://slotsiteleri25.com/# en cok kazand?ran slot oyunlar?

  16. Ten Things You Should Not Share On Twitter best seo consultant in london

  17. Wallacefex表示:

    casino bahis siteleri: Canl? Casino Siteleri – guvenilir casino siteleri

  18. Ronaldgibra表示:

    У меня только положительные впечатления о «Бест Вей». Вступил в кооператив в 2017 году. Спокойно, без всякого давления, начал откладывать деньги на квартиру. Когда накопил нужную сумму, смог получить жилье. Всё было честно и по договору. Сейчас, когда читаю всю эту чепуху о мошенничестве, просто не понимаю, о чём речь. Все выплаты были прозрачные, а люди, которые жалуются, явно не следили за своим процессом. Я с семьей живу в новой квартире, и ни разу не пожалел о своём решении.

  19. https://www.telqq.com Telegram群组,Telegram群组导航。收录Telegram上的优质频道和群组,打造一个高质量Telegram导航。TGNAV收录整理了Telegram上的许多优质频道、群组、机器人,帮助用户发现更多优质的群组。

發佈留言

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