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 must say that it is a superb post..Really we are impressed out of this post….the one who create this post it had been an amazing human. I put one of the links to your blog inside my site, we do hope you don’t mind?
You’re the best, I just found your blog and wanted to say that I’ve truly enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again very soon!
14 Businesses Are Doing A Fantastic Job At Best CSGO Opening Site Counter-Strike Cases [Clients1.Google.Co.Jp]
Why Do So Many People Would Like To Learn More About Text Rewritter?
rewrite Article ai
I don’t accept as true with this particular blog post. Nonetheless, I did searched with Google and I’ve found out that you’re correct and I seemed to be thinking in the wrong way. Carry on publishing top quality articles like this.
Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is wonderful blog. A great read. I’ll certainly be back.
buy cialis usa showed that while 5 albumin and HES both caused an increase in serum creatinine when used as CPB priming fluid, the difference was significantly higher with HES at 72 h 0
Thank you for the sensible critique. Me and my friend were just preparing to do a little research on this. We got a book from our area library but I think I learned more from this post. I am very glad to see such magnificent information being shared freely out there..
Glad to be one of the visitants on this awing site : D.
Magnificent website. Plenty of useful information here. I’m sending it to a few pals ans also sharing in delicious. And obviously, thanks to your sweat!
i am overly conscious about food calories because i would hate to become fat and flabby in the future;
Hello, i study your blog often and i own an analogous one and i used to be just wondering if you get much of spam comments? If so how do you catch it, any plugin or anything you’ll be able to advise? I get thus often lately it’s driving me crazy so any help is very abundant appreciated. for older folks, retirement or a huge promotion at work is a time when celebration events are going to be a great idea.
Hiya, I’m really glad I have found this info. Nowadays bloggers publish just about gossips and web and this is really frustrating. A good blog with exciting content, that is what I need. Thank you for keeping this site, I’ll be visiting it. Do you do newsletters? Cant find it.
Thank you for some other magnificent article. The place else could anyone get that kind of info in such a perfect manner of writing? I have a presentation subsequent week, and I am at the look for such information.
had issues with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.
You have observed very interesting details! ps nice internet site.
An intriguing discussion will be worth comment. I’m sure that you can write much more about this topic, may possibly not be a taboo subject but generally consumers are not enough to chat on such topics. Yet another. Cheers
being a blogger myself . i can see someone with great potential.
This amazing put up usually get a wide selection of guests. Find out how to market it? The situation offers a excellent one-of-a-kind turn relating to matters. Just maybe developing point honest and / or a lot of giving information about is the main event.
I want to point out my gratitude for your kindness for visitors who need assistance with in this study. Your personal dedication to passing the solution throughout came to be extremely insightful and has in most cases permitted associates just like me to reach their pursuits. Your personal insightful publication signifies so much a person like me and even more to my mates. Warm regards; from each one of us.
Just wish to say your article is as amazing. The clearness in your post is simply nice and i can assume you’re an expert on this subject. Well with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.
Figuring out the best colon cleansers sold right now can be extremely difficult particularly for a beginner. This is largely because you’ll find lots of these products available in the market right now. But provided that you know what to look in the product, then it’ll be easy for you. A few essential things to check are the list of components, product reviews, the producer, and the promos they feature.
An impressive share, I just now with all this onto a colleague who had been doing little analysis about this. And he in truth bought me breakfast due to the fact I discovered it for him.. smile. So i want to reword that: Thnx with the treat! But yeah Thnkx for spending some time to talk about this, I feel strongly regarding this and love reading much more about this topic. If possible, as you grow expertise, do you mind updating your site with an increase of details? It truly is highly useful for me. Large thumb up because of this article!
Hi there! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyhow, I’m definitely delighted I found it and I’ll be book-marking and checking back often!
If you’re interested in having a guest blog websiteer please let me recognize. I’ll give you with unique content for your webstie, thanks.
“Quality is everything, so we need to ensure that there are values on what we are sharing to keep our subscribers interested. ” CHECK THIS
Dzięki za jasne i zwięzłe informacje na temat SEO.
buy piracetam pills – secnidazole brand sinemet 20mg for sale
Doceniam skupienie się na zagrożeniach SEO i potrzebie ich usunięcia.
Dzięki za praktyczne wskazówki dotyczące bezpiecznego SEO. Bardzo przydatne!