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

13,999 Responses

  1. Williszew表示:

    https://interpharmonline.shop/# reliable canadian pharmacy

  2. JamesGag表示:

    canadian pharmacy online store: InterPharmOnline – canada drugstore pharmacy rx

  3. Arthurhow表示:

    https://interpharmonline.com/# canadian drug pharmacy
    buying from canadian pharmacies

  4. Anton Elgert表示:

    This is a great article!

  5. DonaldTyclE表示:

    equilibrando
    Equipos de equilibrado: importante para el operación fluido y óptimo de las dispositivos.

    En el entorno de la innovación contemporánea, donde la efectividad y la seguridad del equipo son de alta significancia, los dispositivos de balanceo juegan un rol esencial. Estos aparatos especializados están creados para equilibrar y asegurar componentes móviles, ya sea en herramientas manufacturera, vehículos de transporte o incluso en dispositivos hogareños.

    Para los profesionales en mantenimiento de sistemas y los profesionales, manejar con sistemas de equilibrado es fundamental para proteger el funcionamiento fluido y seguro de cualquier mecanismo giratorio. Gracias a estas soluciones innovadoras innovadoras, es posible reducir sustancialmente las sacudidas, el estruendo y la esfuerzo sobre los rodamientos, prolongando la longevidad de piezas caros.

    Asimismo trascendental es el rol que cumplen los equipos de ajuste en la asistencia al cliente. El asistencia técnico y el mantenimiento constante usando estos equipos facilitan brindar prestaciones de alta estándar, aumentando la agrado de los compradores.

    Para los propietarios de proyectos, la contribución en estaciones de balanceo y dispositivos puede ser fundamental para incrementar la productividad y eficiencia de sus dispositivos. Esto es especialmente relevante para los inversores que manejan modestas y medianas empresas, donde cada detalle vale.

    Por otro lado, los dispositivos de calibración tienen una vasta uso en el campo de la protección y el control de estándar. Posibilitan localizar posibles fallos, impidiendo reparaciones costosas y daños a los aparatos. Más aún, los datos extraídos de estos sistemas pueden usarse para perfeccionar procedimientos y aumentar la presencia en motores de búsqueda.

    Las áreas de implementación de los equipos de equilibrado cubren diversas áreas, desde la manufactura de transporte personal hasta el monitoreo ecológico. No afecta si se habla de extensas fabricaciones industriales o modestos establecimientos caseros, los dispositivos de calibración son esenciales para asegurar un funcionamiento efectivo y sin presencia de detenciones.

  6. Williszew表示:

    https://mexicanpharminter.shop/# MexicanPharmInter

  7. Joshuaerult表示:

    The crypto industry is advancing. (Just don’t ask it where it’s going.)
    trust wallet
    After a dramatic start to the year, the crypto industry is settling into a new reality — one in which the White House is laying out the red carpet and promising an unprecedented level of support.

    Crypto, a roughly 15-year-old industry that’s largely operated on the fringes of finance, is at a crossroads. For years, it has blamed a hostile regulatory environment for not allowing it to unleash its supposedly revolutionary technology on Americans. Now, though, their favorite bogeyman, Gary Gensler, the Securities and Exchange Commission chief under President Joe Biden, is gone. Crypto cheerleaders have been installed throughout the government.

    The SEC has dropped several enforcement cases against crypto companies and, starting Friday, is hosting a series of public roundtables “to discuss key areas of interest in the regulation of crypto assets.”

    Under President Donald Trump, there’s virtually nothing stopping crypto companies from creating and selling their products.

    At the same time, the same White House’s chaotic trade policy is undermining financial markets’ appetite for risk, leaving bitcoin in limbo, more than 20% off from its record high in January. And while the industry is grateful for all the attention, the White House’s embrace of some of crypto’s less savory aspects, like meme coins, has given serious investors pause.

    Given the enormous potential for the $3 trillion industry in this moment, I checked in with Eswar Prasad, a Cornell University professor of international trade and the author of the 2021 book “The Future of Money,” about the forces disrupting financial technologies.

    Fundamentally, Prasad brings a pragmatist’s view of crypto that is as refreshing as it is rare in a subject area that tends to attract zealots and loudmouths. We spoke over the phone shortly after the first-of-its-kind White House crypto summit earlier this month.

    The following interview has been edited for length and clarity.

    Nightcap: We just saw a pretty wild thing happen with the crypto summit — hard to imagine a scenario like that taking place under any previous administration. What were your takeaways?

    Eswar Prasad: The crypto industry is kissing the ring, and I think it’s getting exactly what it wants from the Trump administration, which is the legitimacy provided by government oversight, coupled with what is almost certain to be quite light touch and non-inclusive regulation.

    And I think we saw many of the major players in the crypto industry essentially using the opportunity to not just thank Trump, but try to make the point, which seemed to resonate with Trump, that this industry can power, in some sense, a resurgence of a certain part of the US economy.

  8. Tuấn Kiệt表示:

    I couldn’t agree more! This is a perspective I’ve seen discussed in detail on Zomclub, and I think it brings a fresh outlook on the matter.

  9. Arthurhow表示:

    https://indiamedfast.shop/# cheapest online pharmacy india
    canada pharmacy reviews

  10. JamesGag表示:

    mexican pharmacy online order: Mexican Pharm International – buying from online mexican pharmacy

  11. Williszew表示:

    https://interpharmonline.shop/# canada pharmacy online legit

  12. Arthurhow表示:

    https://indiamedfast.shop/# lowest prescription prices online india
    canadian pharmacy online

  13. Umnvzs表示:

    medrol cost – brand lyrica aristocort for sale

  14. JamesGag表示:

    best online canadian pharmacy: Certified International Pharmacy Online – precription drugs from canada

  15. Williszew表示:

    https://interpharmonline.com/# canadian pharmacy 24

  16. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт планшетов в Москве в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  17. Georgewhend表示:

    mexican pharmacy online store: mexican pharmacy online store – MexicanPharmInter

  18. CharlesArize表示:

    Exponent Finance is redefining DeFi lending by providing secure, transparent, and high-yield investment solutions. Through smart contract-powered lending pools, Exponent Finance DeFi platform allows users to borrow and lend crypto assets with optimal efficiency and minimal risk. Whether you’re looking to earn passive income through staking or access instant liquidity, Exponent Finance offers a decentralized, non-custodial, and user-friendly solution to meet all your financial goals in the crypto ecosystem. https://exponent.ink

  19. RonaldRoora表示:

    Elara Finance is transforming decentralized lending by offering secure, transparent, and flexible crypto loan solutions. Built on blockchain technology, Elara Finance enables users to borrow and lend digital assets seamlessly without intermediaries. With low-interest rates, automated smart contracts, and a permissionless DeFi environment, Elara Finance is making crypto lending accessible and profitable for investors worldwide. https://elara.ink

  20. Arthurhow表示:

    http://mexicanpharminter.com/# mexican pharmacy online
    canadian drugstore online

  21. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт планшетов в Новосибирске в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  22. Franklor表示:

    Cytonic is revolutionizing blockchain security with advanced cybersecurity solutions tailored for Web3 applications. By integrating decentralized encryption, AI-powered threat detection, and smart contract auditing, Cytonic ensures maximum protection against cyber threats. Whether you’re securing DeFi protocols, NFTs, or enterprise blockchain systems, Cytonic’s cutting-edge security technology provides the highest level of data integrity and protection. https://cytonic.cc

  23. DannyTwisp表示:

    Flaunch is the leading blockchain gaming launchpad, designed to help game developers and investors thrive in the Web3 gaming ecosystem. By offering secure token launches, NFT integrations, and decentralized crowdfunding, Flaunch enables game creators to fund, develop, and scale their projects with full transparency and community-driven support. Whether you’re a developer or an investor, Flaunch provides the tools to connect and grow in the blockchain gaming space. https://flaunch.tech

  24. Williszew表示:

    http://interpharmonline.com/# pharmacy rx world canada

  25. Randallvot表示:

    DEQ Finance is revolutionizing decentralized trading by offering a seamless, secure, and efficient crypto exchange experience. Built with cutting-edge blockchain technology, DEQ Finance provides traders with fast transaction speeds, deep liquidity, and a transparent trading environment. Whether you’re a beginner or a professional trader, DEQ Finance delivers high-performance DeFi solutions tailored to modern trading needs. https://deq.li

  26. Arthurhow表示:

    http://interpharmonline.com/# canadian pharmacy prices
    canadian pharmacies online

  27. JamesGag表示:

    mexican pharmacy online: MexicanPharmInter – buying from online mexican pharmacy

  28. Williszew表示:

    https://mexicanpharminter.shop/# buying from online mexican pharmacy

發佈留言

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