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>
I’m impressed, I must say. Truly rarely do I encounter a blog that’s both educative and entertaining, and without a doubt, you might have hit the nail within the head. Your notion is outstanding; ab muscles something that insufficient persons are speaking intelligently about. We’re very happy that I found this in my seek out something with this.
I too conceive thus, perfectly composed post! .
what i can i say, pizza restaurants are really the best and they can really fill my belly**
You’ll Be Unable To Guess Online Shopping Sites Top 7’s Benefits online Shopping sites top 7
An intriguing discussion will probably be worth comment. I think that you simply write much more about this topic, it might become a taboo subject but generally consumers are inadequate to communicate in on such topics. To another. Cheers
This would be the right blog for everyone who is wants to find out about this topic. You already know a great deal its practically tricky to argue on hand (not that I really would want…HaHa). You actually put the latest spin on the topic thats been written about for several years. Excellent stuff, just excellent!
The Top Online Shopping Sites List For Clothes Gurus Can Do Three Things Squeaky Dog Toy With Chew Guard
Hello, Neat post. There’s an issue together with your website in internet explorer, would test this… IE still is the market chief and a huge portion of people will omit your magnificent writing due to this problem.
Oh my goodness! an incredible article dude. Thank you Nevertheless I am experiencing challenge with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting identical rss downside? Anybody who knows kindly respond. Thnkx
12 Stats About Cerebral Palsy Litigation To Make You Think Smarter About Other People
Cerebral Palsy Lawsuits
10 Easy Ways To Figure The Adhd Assessments Uk You’re Looking For Camhs Adhd Assessment Uk
15 Interesting Facts About Jackpot Slots The Words You’ve
Never Learned casino slots Guide (https://Perfectworld.Wiki/)
9 Things Your Parents Teach You About Double Glazed Window Suppliers Near Me Double Glazed Window Suppliers Near Me
15 Reasons You Shouldn’t Be Ignoring Online Shopping Sites For
Clothes us online Shopping sites for clothes
I would like to show my love for your kindness for those who should have help on in this topic. Your personal dedication to passing the message throughout appeared to be astonishingly useful and have usually enabled most people much like me to attain their targets. Your valuable useful information denotes this much a person like me and especially to my office colleagues. Thank you; from all of us.
14 Common Misconceptions About Window Repair Near Me window repairs near me;
http://fourtoons.com/bbs/board.Php?bo_table=free&wr_id=531163,
I think this is among the most important information for me. And i’m glad reading your article. But want to remark on few general things, The web site style is wonderful, the articles is really nice : D. Good job, cheers
What’s The Job Market For Slots For Fun Professionals?
Slots For Fun
An intriguing discussion is worth comment. I think that you ought to write read more about this topic, it might not often be a taboo subject but usually persons are not enough to chat on such topics. To the next. Cheers
you have got a excellent weblog here! want to develop invite posts on my weblog?
you have got a excellent weblog here! would you like to have invite posts on my blog?
I really like your website.. pleasant colors & theme. Performed anyone design this website yourself or even did a person hire an attorney to make it work for you personally? Plz act in response since I!|m planning to style and design my personal weblog and also would want to realize wherever you became that from. thanks
9 Lessons Your Parents Teach You About Upvc Window Repairs Upvc window repairs
10 Tips For How To Get Diagnosed With ADHD In Adults
That Are Unexpected adhd diagnosis cost uk
How To Beat Your Boss On Shopping Online Uk Elegant Wooden Gate For Pets
The 12 Most Unpleasant Types Of Adhd Medication Ritalin People You Follow
On Twitter Types of adhd medication
A Look At The Good And Bad About Website Ranking Software seo traffic software (http://www.diywiki.Org)
You’ll Never Be Able To Figure Out This Online Shopping Uk Amazon’s Secrets Online Shopping Uk
Amazon – http://Importpartsonline.Sakura.Tv –
5 Uk Online Shopping Sites For Mobile Lessons From Professionals Steve Madden Black Leather Loafers (Constance)
See What Glass Door Repair London Tricks The Celebs Are Utilizing glass door repair London