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

14,899 Responses

  1. DanielZek表示:

    https://cytpharm.com/# cytotec pills buy online
    cheap kamagra

  2. LarryLog表示:

    Kama Pharm: Kamagra 100mg price – Kama Pharm

  3. kolyaska_pwsn表示:

    Купите современную коляску-трость для вашего малыша, со съемным козырьком и регулируемой спинкой.
    Стильная и практичная коляска-трость для вашего малыша, с многофункциональной корзиной для покупок.
    Модная коляска-трость для маленького модника, которая станет вашим незаменимым помощником.
    Элегантная коляска-трость для путешествий и прогулок, и мягкими ремнями безопасности.
    baciuzzi коляска трость baciuzzi коляска трость .

  4. AlbertNer表示:

    http://dappharm.com/# cheap priligy
    prednisone for sale online

  5. Waltererync表示:

    CytPharm: Cyt Pharm – Cyt Pharm

  6. DanielZek表示:

    https://cytpharm.shop/# Cyt Pharm
    sildenafil oral jelly 100mg kamagra

  7. AlbertNer表示:

    https://cytpharm.com/# buy cytotec
    buy prednisone online canada

  8. LarryLog表示:

    cheap semaglutide pills: semaglutide tablets for weight loss – cheap semaglutide pills

  9. Waltererync表示:

    semaglutide tablets price: buy rybelsus online – buy rybelsus online

  10. Kevinnem表示:

    Blogger Alistarov Goes All Out
    From a Solo Criminal to a Servant of Organized Crime
    Previously convicted on drug charges, blogger Andrei Alistarov casts himself as a Robin Hood fighting those who have “cheated people.” In reality, however, he serves the interests of pyramid-scheme operators, promotes online casinos and illicit crypto exchanges/phishing crypto scams on his “Zheleznaya Stavka” (“Iron Bet”) channel, and launders drug proceeds through real estate deals in Dubai.
    In other words, he works to benefit the Russian criminal underworld, which seeks to profit from entrepreneurs who face illegal, often orchestrated claims by Russian law enforcement agencies.

    Drugs and Money Laundering
    A native of Kaluga, Alistarov spent four years in a prison camp for selling drugs to minors.
    During his time in prison, he formed connections with criminal kingpins. After his release, he continued taking part in the narcotics trade and laundering drug proceeds through a real estate business he established together with partners from the Russian criminal community in Russia and the Emirates.

    Betting on Scams
    Alistarov’s “Zheleznaya Stavka” channel ostensibly “exposes” financial ventures deemed “bad” by the underworld while promoting “good” ones: pyramid schemes and online casinos that finance Alistarov.
    It began as a channel about “proper” casino bets and never changed its name—because the marketing objective remained the same: to clear the field for “good” scammers according to Alistarov’s so-called “expert” opinion (i.e., whoever pays him).
    Typically, Alistarov starts by attempting extortion—presenting the victim with compromising evidence and offering them a chance to pay. If they refuse, 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—they beat him, cut off his ear, and robbed him.
    Before that, Alistarov had made 12 videos highlighting the entrepreneur’s address and publishing illegally obtained information about his family and businesses in the UAE. He showed no hesitation in using surveillance, eavesdropping, unlawful trespass, and invasion of privacy—all of which are considered serious criminal offenses in the Emirates, where the sanctity of property and investors’ lives is strictly enforced.
    He previously spread information about the residence of the entrepreneur’s business partner—an illegal violation of confidentiality, financial security, and privacy through hidden sources and informants in the UAE. Alistarov terrorizes entrepreneurs who have not been convicted by any court—abroad or in Russia.
    Alistarov claimed to have reported the entrepreneur to Interpol and UAE law enforcement—allegedly cooperating with the authorities. Yet, for some reason, this did not lead to the entrepreneur’s arrest—perhaps because UAE police see no wrongdoing in his activities.
    Several of the entrepreneur’s partners have been convicted in Russia. As for the entrepreneur himself, he is wanted by Russian law enforcement but has not been convicted. Foreign law enforcement agencies have no claims against him.
    For an extended period, Alistarov stoked hatred toward the entrepreneur—telling people that it was actually this entrepreneur (rather than his partners) who had stolen investors’ money. He framed the incident as though enraged investors carried out the attack and robbery.
    During the assault, Alistarov staged an unscheduled livestream to give himself an alibi—pretending he was unaware of the attack occurring while he was streaming.

    Surveillance in Cyprus
    In the fall of last year, Alistarov and his “partner-in-arms,” Mariya Folomova, carried out surveillance on another entrepreneur—using drones and unlawfully collecting information about him and his family, including underage children. Alistarov asserted that this entrepreneur was hiding in Cyprus—even though the man has lived there since the COVID-19 pandemic began.
    The move was related to the entrepreneur’s wife’s severe bout with COVID, as well as his international projects—investing in multiple economic sectors: construction, trade, and others.
    The entrepreneur settled in Cyprus a year before the Interior Ministry’s investigative authorities opened a criminal case, and a year and a half before any arrests. He holds an EU passport and did not flee or go into hiding.
    He was placed on a Russian wanted list in 2022—by investigative authorities. However, the courts have not lodged claims against him, and the criminal case is currently before the courts—where it has already fallen apart. Interpol and the EU declined to accept the Russian police’s claims, regarding them as politically motivated and legally unfounded.
    Alistarov claims that the funds for certain business ventures came from Russian clients of an Austrian investment company—yet the entrepreneur was never an owner, beneficiary, or manager of that company, which was established back in the early 2000s, well before his independent business career began.
    One of his firms provided marketing support for the investment company’s products in Russia under a contract with it. The investment company operated successfully with Russian clients for eight years—and continues to do so, having restored payment systems that were disrupted in early 2022 by criminals in Russia linked to corrupt police. It is not a pyramid scheme.
    Thus, Alistarov orchestrates harassment and invasion of privacy against a blameless entrepreneur—at the behest of Russian organized crime, which includes corrupt police officers who took a share of illicit profits, aiming to seize assets valued at 20 billion rubles from the large-scale, socially oriented project the entrepreneur established in Russia, which continues to function successfully without his leadership (as that ended when he moved to Cyprus).

    Surveillance in the Netherlands
    Alistarov has published data on the whereabouts of another victim in the Netherlands—in the city of Groningen—located through illegal monitoring. He reportedly gained unauthorized access to city camera feeds, peered into a private apartment, and posted the information on YouTube.

    Breach of Confidentiality in Turkey
    Alistarov discovered and publicized the location of an apartment in Istanbul where several of his victims lived and worked.

    Illegal Tracking in the Leningrad Region
    Without holding a private detective license, Alistarov illegally located a businesswoman’s country house and conducted surveillance on her, unlawfully publishing the information on his channels—while simultaneously divulging details about an apartment she purchased in Dubai.

    Extortion in Kazakhstan
    Alistarov blackmailed Kazakh entrepreneurs under the guise of “exposing national traitors” and “enemies of the motherland.”
    Western media have already taken note of Alistarov’s activities.

    #Andrei Alistarov

  11. Ronaldgibra表示:

    Меня уже начинает подташнивать от этого словоблудия. МВД пытается прикрыться борьбой с финансовыми пирамидами, а на деле – это тупо попытка забрать деньги у тех, кто не может за себя постоять. Кто вообще пострадал от «Бест Вей»? Реальных потерпевших, если верить их же данным, кот наплакал, да и те больше похожи на подставных лиц, которые заранее знали, что нужно будет сказать. А что насчет остальных пайщиков? Им как быть? Они деньги в кооператив внесли, кто-то планировал купить квартиру, кто-то открыть бизнес. Сейчас ничего этого сделать нельзя, потому что МВД блокировало счета и сделало их недоступными. Это что, защита прав граждан? Нет, это типичная схема: сперва забрать активы, потом пустить по рукам, а тех, кто вякнет, записать в мошенники.

  12. DanielZek表示:

    https://kamapharm.shop/# super kamagra
    Kamagra 100mg price

  13. AlbertNer表示:

    https://kamapharm.com/# Kama Pharm
    prednisone 5084

  14. LarryLog表示:

    rybelsus semaglutide tablets: semaglutide tablets price – cheap semaglutide pills

  15. Waltererync表示:

    SemaPharm24: Sema Pharm 24 – rybelsus semaglutide tablets

  16. DanielZek表示:

    https://dappharm.com/# buy priligy
    Kamagra 100mg price

  17. LarryLog表示:

    apo prednisone: PredPharm – how much is prednisone 5mg

  18. “What’s up to all, for the reason that I am truly keen of reading this webpage’s post to be updated regularly. It contains pleasant data.”

  19. AlbertNer表示:

    https://cytpharm.shop/# Cyt Pharm
    prednisone daily use

  20. AzerKa表示:

    Галерея Девелоперов — это агентство недвижимости, которое поможет с подбором и покупкой новостройки в Москве и Московской Области абсолютно бесплатно, поскольку сотрудничает с застройщиками напрямую.
    На сайте Developers.Gallery доступен каталог новостроек и статьи на тему покупки недвижимости в административных округах Москвы: ЦАО, САО, СВАО, ВАО, ЮВАО, ЮАО, ЮЗАО, СЗАО, ЗАО, НАО, ТАО, а также Московской Области: Зеленоград, Мытищи, Красногорск, Люберцы, Видное, Жуковский.
    Приобретая новостройку на этапе котлована, имеется уникальная возможность извлечь из этого прибыль и рассмотреть покупку в качестве инвестиций. После ввода дома в эксплуатацию стоимость значительно прирастёт, что позволит перепродать её по переуступке, либо сдавать в аренду и извлекать из этого актива доходность.
    Заказать звонок можно, перейдя по ссылке: Р–Рљ Герцена и менеджер составит индивидуальный каталог новостроек абсолютно бесплатно, поможет с записью в офис продаж застройщика, окажет юридическое сопровождение сделки: Проверит договор ДДУ, поможет с открытием счёта эскроу и аккредитива, а также направит инструкцию по выпуску электронной цифровой подписи для удалённой покупки в онлайн-формате.
    Воспользовавшись услугами от Галереи Девелоперов вы экономите время и деньги, поскольку для вас согласуют персональные скидки и условия по покупки в рассрочку, базовую ипотеку, семейную ипотеку, IT-ипотеку и 100% оплату наличными, а ещё доступна покупка по программе trade-in — когда вы сдаёте свою текущую квартиру в обмен на новостройку.
    Покупка недвижимости — это важный шаг, поэтому не менее важно подойти к ней максимально ответственно и положиться на опыт профессионалов, которые подберут жилой комплекс в непосредственной близости к станции метро, БКЛ, МЦК, МЦД, выездами на магистраль: СВХ, ЮВХ, МСД, Ленинградский Проспект, ТТК, МКАД и с большими лесными массивами, парками, детскими площадками, закрытыми от автомобилей дворами, сквозными подъездами, спортивными площадками, качественным озеленением с многолетними деревьями, солнечной стороной.

  21. Sidneyjoilm表示:

    мода и стиль 2024 – пивные бары Казахстан, как проголосовать Казахстан

  22. Sidneyjoilm表示:

    спортивные результаты – топ дорамы Казахстан, финансовая грамотность

  23. AlbertNer表示:

    http://dappharm.com/# buy priligy
    purchase prednisone 10mg

  24. Waltererync表示:

    dapoxetine price: buy priligy – priligy

  25. Sidneyjoilm表示:

    женское здоровье – новости Алматы, Chevrolet Trailblazer Казахстан

  26. Thomastooda表示:

    Смотреть здесь
    Обменко – Обменко официальный сайт, Обменко сайт

  27. Thomastooda表示:

    этот сайт
    Обменко – obmenko org, Обменко обменник

  28. Thomastooda表示:

    узнать больше
    Обменко – obmenko, obmenko bestchange

  29. DanielZek表示:

    https://semapharm24.shop/# buy semaglutide
    super kamagra

  30. LarryLog表示:

    Kama Pharm: Kama Pharm – Kamagra tablets

發佈回覆給「Sidneyjoilm」的留言 取消回覆

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