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

  1. Williamgox表示:

    Many casinos have beautiful ocean views. http://jugabet.xyz/# Los casinos celebran festivales de juego anualmente.

  2. 有道词典是由网易有道出品的全球首款基于搜索引擎技术的全能免费语言翻译软件。简介. 支持中文、英语、日语、韩语、法语、德语、俄语、西班牙语、葡萄牙语、藏语、西语等109种语言翻译。拍照翻译、语音翻译、对话翻译、在线翻译、离线翻译更顺畅。更多的翻译 https://www.fanyim.com

  3. Lannyhat表示:

    п»їCasinos in the Philippines are highly popular.: taya365 – taya365 login

  4. JosephCyday表示:

    phtaya casino phtaya Gambling can be a social activity here.

  5. 10 Things That Your Family Taught You About Asbestos Exposure Attorney Mesothelioma Lawyers

  6. Ten Easy Steps To Launch Your Own Sash Window Refurbishment Business sash windows repair
    (https://humanlove.stream)

  7. Williamgox表示:

    Game rules can vary between casinos. http://taya365.art/# High rollers receive exclusive treatment and bonuses.

  8. Davidzem表示:

    https://phmacao.life/# Promotions are advertised through social media channels.
    Online gaming is also growing in popularity.

  9. JosephCyday表示:

    taya365 login taya365 Gambling regulations are strictly enforced in casinos.

  10. Davidzem表示:

    http://taya777.icu/# The casino atmosphere is thrilling and energetic.
    Responsible gaming initiatives are promoted actively.

  11. Patrickspogs表示:

    п»їCasinos in the Philippines are highly popular.: phtaya.tech – phtaya casino

  12. Patrickspogs表示:

    Hay reglas especГ­ficas para cada juego.: winchile casino – winchile.pro

  13. Lannyhat表示:

    Las estrategias son clave en los juegos.: jugabet.xyz – jugabet casino

  14. Williamgox表示:

    Gaming regulations are overseen by PAGCOR. http://winchile.pro/# п»їLos casinos en Chile son muy populares.

  15. Lannyhat表示:

    Players often share tips and strategies.: taya365 login – taya365 login

  16. Davidzem表示:

    https://jugabet.xyz/# Las estrategias son clave en los juegos.
    Loyalty programs reward regular customers generously.

  17. Круглосуточная поставка алкоголя в Москве: удобство либо проблема?

    Москва – город, который никогда никак отдыхает, а для большинства его населения шанс приобрести желаемое в всякое время дня явилась привычной. Это принадлежит также к поставке алкоголя, что, несмотря на ее спорность, прочно проникла в повседневную жизнь столичных жителей. Но так ли всё просто, словно кажется с первого раза?

    Как это функционирует?

    Круглосуточная доставка спиртного в Москве осуществляется посредством многообразные службы:

    Интернет-сервисы: Специализированные сайты и приложения, что дают широкий ассортимент алкогольных продуктов с доставкой в дом. Рестораны и пабы: Некоторые заведения, имеющие разрешение на реализацию спиртного, предоставляют поставку их продукции в вечернее время. Курьерские сервисы: Компании, что сотрудничают с имеющими лицензию реализаторами алкоголя и осуществляют поставку по запросу. Преимущества:

    Удобство: Возможность заказать любимый напиток, не выходя из дома, в всякое время суток. доставка алкоголя ночью москва Экономия времени: Не нужно тратить время на поход в магазин, особенно в вечернее время. Широкий ассортимент: Обширный ассортимент алкогольных продуктов, в том числе необычные и эксклюзивные предложения. Шанс для вечеринок и мероприятий: Быстрая доставка позволяет оперативно пополнить запасы алкоголя, когда это потребуется. Недостатки и противоречия:

    Законность: В России не разрешена реализация спиртного в ночное время (с 23:00 до 8:00). Службы доставки, которые предоставляют круглосуточную поставку, часто применяют различные схемы, что могут оказаться незаконными. Потребление спиртного: Простой получение к алкоголю в всякое время может способствовать росту употребления, что способен повлечь отрицательные последствия для самочувствия. Проверка за реализацией несовершеннолетним: Имеется риск, что курьеры способны не контролировать возраст клиентов, что может вызвать к реализации спиртного несовершеннолетним.

  18. Frankelava表示:

    Welcome to PancakeSwap: A Beginner’s Guide
    PancakeSwap is a decentralized exchange platform on the Binance Smart Chain, designed for swapping BEP-20 tokens. With its vibrant ecosystem, ease of use, and low transaction fees, it’s become a popular choice among crypto enthusiasts.
    Pancakeswap
    What is PancakeSwap?
    PancakeSwap is an automated market maker (AMM) that allows users to trade directly from their crypto wallets. There’s no order book involved; instead, trades are made against a liquidity pool. Here’s how you can get started:

    How to Use PancakeSwap?
    Set Up Your Wallet
    First, you need a crypto wallet like MetaMask or Trust Wallet. Ensure your wallet supports BEP-20 tokens.
    Connect to Binance Smart Chain
    Configure your wallet to connect to the Binance Smart Chain network. Detailed guides are available in your wallet settings.
    Purchase BNB
    You’ll need BNB (Binance Coin) to cover transaction fees. Buy BNB from a reputable exchange and transfer it to your wallet.
    Access PancakeSwap
    Visit the official PancakeSwap website and connect your wallet by clicking on the ‘Connect Wallet’ button.
    Start Trading
    Once connected, you can begin swapping BEP-20 tokens. Choose the tokens you wish to trade and confirm your transactions.
    Benefits of PancakeSwap
    Lower Fees: Operating on Binance Smart Chain, the fees are more affordable than Ethereum-based exchanges.
    Fast Transactions: Experience quick transaction speeds due to the efficiency of BSC.
    Yield Farming: Earn rewards by providing liquidity or participating in various farming pools.
    Conclusion
    PancakeSwap offers a user-friendly approach to trading cryptocurrencies, engaging users with its gamified elements like lotteries and collectibles. Whether you’re a beginner or an experienced trader, PancakeSwap provides an efficient and exciting way to dive into the world of decentralized finance. Always ensure to perform your due diligence before engaging in trading activities.

    For more detailed guides and support, visit the .

  19. Davidzem表示:

    http://winchile.pro/# La historia del juego en Chile es rica.
    Players enjoy both fun and excitement in casinos.

  20. Williamgox表示:

    Many casinos provide shuttle services for guests. http://jugabet.xyz/# La mГєsica acompaГ±a la experiencia de juego.

  21. Patrickspogs表示:

    La diversiГіn nunca se detiene en los casinos.: jugabet chile – jugabet.xyz

  22. Patrickspogs表示:

    Gambling regulations are strictly enforced in casinos.: taya777 – taya777 login

  23. Charlesrot表示:

    Optimize Your Crypto Trading with TraderJoeXyz
    In the dynamic world of cryptocurrency, having the right tools at your disposal can make all the difference. Enter TraderJoeXyz, a cutting-edge platform designed to maximize your trading potential. By leveraging TraderJoeXyz, traders gain access to a multitude of features that cater to both beginners and seasoned professionals. Let’s explore how TraderJoeXyz can enhance your crypto trading journey.
    traderjoexyz
    Features of TraderJoeXyz
    The TraderJoeXyz platform is packed with robust features aimed at simplifying and optimizing cryptocurrency trading:

    Advanced Trading Interface: The user-friendly interface is equipped with powerful tools to execute trades efficiently.
    Comprehensive Analytics: Gain insights with detailed analytics and customizable charts for better decision-making.
    Secure Wallet Integration: Seamlessly manage your crypto assets with integrated security measures.
    Automated Trading Bots: Use AI-driven bots to enhance your trading strategy with automated buy and sell actions.
    Benefits of Using TraderJoeXyz
    Here are some of the benefits you can expect when using TraderJoeXyz:

    Increased Efficiency: With streamlined processes and intuitive design, traders can execute trades faster than ever.
    Greater Profit Potential: Advanced tools and analytics help you identify profitable trading opportunities.
    Reduced Risk: Implementing secure wallet integrations and automated bots can help mitigate risks associated with trading.
    Enhanced Trading Experience: A seamless interface paired with powerful tools ensures an exceptional trading journey.
    Join the TraderJoeXyz Community
    TraderJoeXyz is more than just a platform; it’s a community of crypto enthusiasts and experts. Joining this community provides access to shared knowledge, support, and collaboration opportunities. To become part of this thriving ecosystem, simply and start exploring the world of crypto trading today.

    By choosing TraderJoeXyz, you’re not just trading—you’re transforming your crypto experience. Get started and make the most of your cryptocurrency assets.

  24. Lannyhat表示:

    The thrill of winning keeps players engaged.: taya777.icu – taya777 login

  25. JosephCyday表示:

    win chile winchile casino Las reservas en lГ­nea son fГЎciles y rГЎpidas.

  26. Matthewtrurn表示:

    Introducing Velodrome Finance: Maximize Your Crypto Yields
    In the rapidly evolving world of decentralized finance (DeFi), Velodrome Finance emerges as a robust platform for enthusiasts looking to enhance their crypto yield returns. This guide will walk you through the essentials of Velodrome Finance and how you can benefit from its features.
    velodrome finance
    Why Choose Velodrome Finance?
    Velodrome Finance stands out as a comprehensive DeFi protocol designed specifically for liquidity providers. Its innovative approach focuses on maximizing rewards while maintaining efficient and secure trading mechanisms. Here’s why it’s capturing the attention of the DeFi community:

    Efficient Token Swaps: Velodrome offers seamless and cost-effective token swapping capabilities.
    Liquidity Pools: Participants can provide liquidity to various pools, optimizing their earning potential.
    Yield Optimization: With advanced strategies, Velodrome helps users achieve superior returns on their investments.
    Secure Protocol: Security is a top priority, and Velodrome utilizes cutting-edge technology to protect user assets.
    Getting Started with Velodrome
    Embarking on your journey with Velodrome Finance is straightforward. Here’s a step-by-step guide to help you dive into the platform:

    Create a Wallet: To engage with Velodrome, you first need a compatible crypto wallet.
    Connect Your Wallet: Visit and securely link your crypto wallet.
    Explore Liquidity Pools: Browse through available pools and decide where to allocate your assets for optimal returns.
    Stake and Earn: Once you’ve funded a pool, begin staking and watch your earnings grow as you benefit from trading fees and incentives.
    Community and Support
    Velodrome Finance boasts a vibrant community ready to assist users at any step. Whether you’re a seasoned DeFi user or a newcomer, you can find guidance and support from community forums and dedicated customer service.

    Conclusion
    With its focus on maximizing crypto yield, Velodrome Finance is a compelling choice for anyone looking to delve deeper into the DeFi space. From efficient token swaps to robust security measures, it offers a complete ecosystem for those eager to optimize their returns. Visit the official site and start your journey towards enhanced financial growth.

  27. Начни на Фактические Средства с Комфортом! Онлайн покер – является не только игра, это полная мир волнения, стратегии а шанса заработать реальные деньги, без выходя из квартиры. Если ты пытаетесь где поиграть на покер в интернете, на русском языке а с выводом денег непосредственно на карту, значит вы попали нужному адресу. Эта статья – ваш гид в мир онлайн покера в россии.

    Отчего Онлайн Покер настолько Известен? Покер – есть традиционная карточная игра, что веками завлекала миллионы людей. Онлайн формат дал ей новую жизнь, сделав игры доступными для каждого жаждущих. Вот только пара причин известности онлайн покера:

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

    Популярные Покеррумы для Русских Игроков:

    Мы организовали рейтинг лучших покеррумов для русском языке игроков, учитывая следующие критерии:

    Наличие русского языка: Интерфейс и обслуживание должны быть на русском языке. Возможность играть на рубли: Депозиты а вывод средств должны быть открыты в рублях. Многообразие игр и турниров: Широкий выбор столов и турниров для всевозможных уровней игроков. Наличие мобильного приложения: Возможность скачать приложение для андроид и играть с мобильного устройства. Наличие выгодных бонусов: Бездепозитным бонусом за регистрацию, начальным капиталом, бонусы на депозит и другие акции. Безопасность и авторитет: Безопасность транзакций и честность игры. Топ румов регулярно обновляется, поэтому советуем наблюдать за свежими обзорами а отзывами игроков.

    Особое Внимание на Минимальный Депозит:

    Когда ты новичок, тогда следует обратить внимание на покеррумы с минимальным депозитом. Данное даст возможность вам начать играть на реальные деньги без больших финансовых вложений.

    Разрешенные Покеррумы:

    Убедитесь, что выбранный вами рум является допущенным в россии, для того чтобы избежать вероятных проблем с доступом и выводом средств.

    Онлайн Покер с Выводом Денег на Карту: Как Это Работает? После того, как ты определились с покеррумом а подобрали игру, вы способен положить твой счет и начать играть на деньги. Большая часть сайтов дают различные способы пополнения а вывода средств, включая:

    Банковские карты (Visa, Mastercard) Электронные кошельки Другие платежные системы Вывод денег на карту как правило занимает от нескольких часов до нескольких дней, в зависимости от рума а выбранного способа вывода.

    Как Играть в Онлайн Покер с Друзьями? Многие покеррумы дают шанс играть с друзьями за закрытыми столами. Это замечательный метод уделить время с людьми, с которыми ты знакомы, а побороться за титул лучшего игрока в твоей компании.

    Бесплатный Покер: Возможность Попробовать Свои Силы Когда вы новичок и желаешь сначала привыкнуть с правилами, многие сайты предлагают возможность играть в бесплатный покер. Это отличный способ потренироваться и получить опыта перед тем, как начать играть на реальные деньги.

    Покер на пк: Комфорт а Удобство Если вы выбираешь играть на пк, то большая часть покеррумов дают программы для компьютеров, что гарантируют намного удобный и надежный игровой процесс.

    Заключение: Начните Свой Путь в Мир Онлайн Покера Сегодня! Онлайн покер – есть захватывающая игра, что способна принести тебе ни просто удовольствие, но и реальные деньги. Выбирайте проверенные сайты и румы, участвуйте в турнирах, играйте с друзьями и людьми со целого мира, и помните, что главное – это получать удовольствие от игры!

    Ни откладывайте на потом, приступайте свою игру в онлайн покер прямо сейчас! Погрузитесь в мир тактики, волнения а шансов! Везенья за столами!

  28. Scotthom表示:

    What is Uniswap?
    Uniswap is a decentralized exchange (DEX) protocol built on the Ethereum blockchain. It enables direct peer-to-peer cryptocurrency transactions, allowing users to trade coins without intermediaries. This makes it a cornerstone of the Decentralized Finance (DeFi) ecosystem.
    uniswap exchange
    Benefits of Using Uniswap
    Uniswap offers several advantages over traditional, centralized exchanges:

    Decentralization: Users maintain control of their funds, minimizing the risk of hacking or fraud associated with central exchanges.
    Liquidity Pools: Uniswap uses automated liquidity pools instead of traditional order books, enabling seamless and efficient trading.
    Open Access: Anyone with an Ethereum wallet can trade on Uniswap, facilitating financial inclusivity.
    No Registration: Trade instantly without creating an account or passing through identity verification processes.
    How to Use Uniswap
    Getting started with Uniswap is simple and intuitive. Follow these steps:

    Create and fund an Ethereum wallet if you don’t have one. Some popular options include MetaMask, Trust Wallet, and Coinbase Wallet.
    Connect your wallet to the Uniswap platform by navigating to their website and initiating the connection process.
    Choose the tokens you wish to trade. Always ensure you are aware of the gas fees involved in the transaction.
    Initiate the swap and confirm the transaction in your wallet. Your new tokens will be available once the transaction is confirmed on the blockchain.
    Security Tips
    While Uniswap is a secure platform, it’s crucial to follow best practices to ensure your funds remain safe:

    Always ensure you are accessing the legitimate Uniswap website by verifying the URL.
    Keep your wallet’s private keys secure and never share them with anyone.
    Regularly update your cryptocurrency wallet and browser to prevent vulnerabilities.
    Conclusion
    Uniswap has revolutionized the way cryptocurrency trading operates by providing a secure, user-friendly, and inclusive platform. Whether you are a seasoned trader or a newcomer to the crypto world, Uniswap offers a powerful tool for navigating the DeFi landscape.

  29. BradleyThine表示:

    comprare farmaci online con ricetta: Cialis generico – migliori farmacie online 2024
    acquisto farmaci con ricetta

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

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