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

15,802 Responses

  1. Victorprima表示:

    Get warning information here.
    cost cheap cytotec
    Offering a global touch with every service.

  2. Victorprima表示:

    Their health awareness campaigns are so informative.
    gabapentin and mouth problems
    They always offer alternatives and suggestions.

  3. bake表示:

    10 Quick Tips About Single Oven With Grill bake

  4. Luciotox表示:

    Недавно нашел на gizbo сайт,
    и решил рассказать своим опытом.
    Платформа кажется очень привлекательной,
    особенно если ищешь качественное казино.
    Кто уже пробовал Gizbo Casino?
    Поделитесь своим мнением!

    Особенно любопытно узнать про промокоды и акции.
    Допустим, предлагают ли Gizbo Casino особые условия для новых игроков?
    Также интересно, где найти рабочее зеркало Gizbo Casino, если основной сайт недоступен.

    Видел немало противоречивых мнений, но интересно узнать реальные советы.
    Например, где лучше активировать бонусы на Gizbo Casino?
    Расскажите своим опытом!

  5. WalterCherm表示:

    They have an impressive roster of international certifications.
    https://lisinoprilpharm24.top/
    The free blood pressure check is a nice touch.

  6. 10 Meetups On Buy Category B1 Driving License You
    Should Attend Comprar Carta De ConduçãO Da Categoria B1

  7. Jasonzitte表示:

    The most trustworthy pharmacy in the region.
    can i buy generic clomid without rx
    Offering a global gateway to superior medications.

  8. What’s The Job Market For Sell Pallets Near Me Professionals
    Like? sell pallets near me, https://git.mxr612.top/agronytradingllc4113,

  9. WalterCherm表示:

    The pharmacists are always updated with the latest in medicine.
    https://cytotecpharm24.top/
    Their medication synchronization service is fantastic.

  10. Jasonzitte表示:

    The best place for health consultations.
    gabapentin indications use
    Leading the charge in international pharmacy standards.

  11. Stationary Cycle For Exercise Tools To Help You Manage
    Your Daily Lifethe One Stationary Cycle For Exercise Trick That Every
    Person Should Learn stationary cycle For exercise

  12. Victorprima表示:

    I appreciate the range of payment options they offer.
    where buy generic lisinopril no prescription
    Read now.

  13. Victorprima表示:

    Love their spacious and well-lit premises.
    gabapentin purpura
    Their patient education resources are top-tier.

  14. Charlesrom表示:

    ‘I’m very impulsive’: Why this American woman moved to France at the age of 70
    порно секс жесток
    She’d dreamed of living in France for years, but according to Janice Deerwester, originally from Texas, life always seemed to get in the way.

    In 2021, Janice, who has been a widow since 2012, found herself lying on her bed with the lyrics to “Is That All There Is?,” a song about dissatisfaction that was a hit for country singer Peggy Lee back in 1969, playing in her head.

    “I hated that song when it came out, but all of a sudden it came to my mind,” Janice, who was based in Georgia at the time, tells CNN Travel. “I thought, ‘Is this all there is?’ I work, come home tired. I get up. Is this it?”
    Realizing that she wanted more from life, Janice decided there and then that she would relocate to Fontainebleau — the French town she’d had her heart set on since a 2018 visit. Less than a year later, at the age of 70, she did just that.

    “I’m very impulsive so that kind of followed the rule,” she adds.

    Now happily settled in Fontainebleau, located southeast of Paris, Janice feels that she “made the best choice ever” and is incredibly grateful to be living out her fantasy.

    “I am the luckiest woman I feel that ever was,” she says. ”And why I have this, and why I was given this, I have no idea. But I’m just blessed every day that I get to live here.”

    Janice goes on to explain that she wasn’t necessarily unhappy back in Georgia, and enjoyed living on a horse ranch in the country, which she had been renting since selling her home, but was overcome with the feeling that “there’s got to be more” to life.

  15. WalterCherm表示:

    The staff is well-trained and always courteous.
    https://cytotecpharm24.top/
    They consistently exceed global healthcare expectations.

  16. Jasonzitte表示:

    Their 24/7 support line is super helpful.
    buy generic gabapentin
    Their international catalog is expansive.

  17. Jasonzitte表示:

    A pharmacy that’s globally recognized and locally loved.
    can you buy cytotec without a prescription
    Breaking down borders with every prescription.

  18. WalterCherm表示:

    A pharmacy that feels like family.
    https://lisinoprilpharm24.top/
    They make international medication sourcing a breeze.

  19. LarryTus表示:

    Strategy and Planning: How an SEO Agency Sets the Stage for Success
    look
    Before any tangible optimization begins, a reputable SEO agency invests time in research and planning. They evaluate the client’s goals, industry landscape, and competitor positioning. If, for instance, a client aims to capture local customers, the agency may focus on local SEO tactics like Google Business Profile optimization and localized content. On the other hand, an e-commerce client might need a product-centric strategy emphasizing product page optimizations, schema markup, and robust category descriptions. This strategic planning phase is crucial because it ensures that every subsequent action is driven by data, aligning with the client’s broader marketing objectives.

  20. Victorprima表示:

    Professional, courteous, and attentive – every time.
    where can i get clomid no prescription
    A name synonymous with international pharmaceutical trust.

  21. Why Buy A German Driving License Is Harder Than You Think Deutsche FüHrerschein Kaufen

  22. Victorprima表示:

    Been a loyal customer for years and they’ve never let me down.
    can i buy cheap cipro price
    World-class service at every touchpoint.

  23. WalterCherm表示:

    earch our drug database.
    https://clomidpharm24.top/
    A model pharmacy in terms of service and care.

  24. Jasonzitte表示:

    Consistent service, irrespective of borders.
    cost cytotec without a prescription
    Always leaving this place satisfied.

  25. Jamesemulk表示:

    UTLH et le staking : comment gagner 24 % par an sans complications inutilesDans le monde en constante évolution des technologies financières, il n’est pas toujours facile de trouver une source de revenus simple et fiable. La plupart des instruments exigent soit une connaissance approfondie de la DeFi, soit impliquent des risques élevés. UTLH propose une autre approche : un staking transparent et accessible avec un rendement de 24 % par an (2 % par mois). C’est pourquoi des milliers d’investisseurs ont déjà adopté ce token et gagnent avec succès sans perdre de temps ni d’énergie sur des schémas complexes.Pourquoi le staking UTLH est-il avantageux ?1.1. Un rendement élevé avec des risques minimauxUn taux de 2 % par mois permet d’accroître son capital de manière stable, alors que de nombreux placements bancaires classiques ne couvrent même pas l’inflation. Sans complexité superflue : il n’est pas nécessaire de comprendre le farming ou de gérer plusieurs pools de liquidité. Il suffit de stocker les tokens UTLH dans un smart contract et de percevoir des intérêts.1.2. Un modèle économique fiableUne émission limitée (957 315 tokens) et des mécanismes de brûlage soutiennent le prix. Une application réelle : le token ne se contente pas d’être échangé, il participe au programme d’Aide Financière Universelle (AFU), garantissant une demande constante.Comment fonctionne le staking UTLH ?Vous achetez des tokens sur une plateforme accessible (DEX ou via l’espace personnel du club). Vous les verrouillez dans un smart contract pour une période déterminée (généralement 12 mois). Vous recevez 2 % par mois, et à l’issue du contrat, votre « capital initial » (quantité de UTLH bloquée) vous est restitué avec le dernier paiement.2.1. Un seuil d’entrée basMême 1 UTLH suffit pour commencer à gagner avec le staking. Cela permet à tout un chacun d’expérimenter l’investissement en cryptomonnaie de manière modérée, sans crainte d’« entrer trop tard » ou « trop cher ».Les avantages d’UTLH par rapport aux autres projets de staking3.1. Un écosystème stableUne communauté fermée (UTL Club) assure une demande continue pour le token : les membres utilisent UTLH comme garantie pour obtenir un financement préférentiel via le programme AFU. Aucune bureaucratie superflue : toutes les opérations se font via des smart contracts, et les conditions de staking sont transparentes et inscrites dans le code.3.2. Protection contre la volatilité du marchéContrairement à de nombreux projets crypto où le cours peut chuter brutalement sous l’effet de la spéculation, UTLH bénéficie de :Une émission limitée : le prix ne se déprécie pas à cause de l’impression de nouveaux tokens.Un mécanisme de brûlage : l’offre diminue lorsque la demande augmente, ce qui soutient le cours.Stratégie à long terme : staking + hausse du prix4.1. Générez un revenu passif immédiatementTant que vous maintenez vos UTLH en staking, vous recevez des intérêts mensuels (2 %). Cela rend déjà l’investissement attractif, car un tel rendement est quasiment introuvable sur le marché traditionnel.4.2. Un gain supplémentaire grâce à l’appréciation de l’actifAvec l’expansion du programme AFU et l’augmentation du nombre de résidents de l’UTL Club, le cours de l’UTLH peut croître, et au moment où vous décidez de retirer vos tokens, leur valeur pourrait être bien plus élevée.Guide simple pour débuterPréparez un portefeuille compatible avec Binance Smart Chain (Trust Wallet ou MetaMask). Achetez des UTLH sur l’une des plateformes recommandées (DEX/CEX ou au sein du club). Accédez à la plateforme de staking UTLH, connectez votre portefeuille et choisissez le nombre de tokens à verrouiller. Confirmez la transaction et commencez à percevoir 2 % dès le mois suivant.Conclusion : pourquoi le staking UTLH est-il si prisé aujourd’hui ?Sécurité : les smart contracts BSC et le code ouvert éliminent les risques cachés.Rendement élevé : 24 % par an est l’une des offres les plus attractives et stables du marché crypto.Un soutien réel : grâce à l’Aide Financière Universelle et à la communauté UTL Club, les détenteurs de tokens ont confiance en son avenir, garantissant une demande durable pour UTLH.Si vous recherchez un revenu passif stable, que vous appréciez la simplicité et la sécurité, alors le staking avec UTLH pourrait être une solution idéale. Rejoignez le projet dès aujourd’hui et laissez votre capital travailler pour vous ! 

  26. Jasonzitte表示:

    Their international collaborations benefit patients immensely.
    can you get cheap clomid without a prescription
    A pharmacy I wholeheartedly recommend to others.

  27. WalterCherm表示:

    I’m grateful for their around-the-clock service.
    https://cipropharm24.top/
    They set the tone for international pharmaceutical excellence.

  28. Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

  29. Enrique表示:

    Ten Apps To Help Control Your Robot Vacuum Cleaner automatic vacuum and mop (Enrique)

  30. Introducing to you the most prestigious online entertainment address today. Visit now to experience now!

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

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