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>
best canadian pharmacy: canadian drug – canada drugs reviews
USACanadaPharm reputable canadian online pharmacy canadian pharmacy meds
usa canada pharm: USACanadaPharm – usa canada pharm
Текст
Пациенты часто выбирают Temptation, когда имеют дело с симптомами, связанными со стрессом, депрессией и хронической болью. Данный сорт имеет такие вкусы, как ваниль, ягоды и дизель. Доминирующим терпеном этого штамма является лимонен. В целом, это мощный сорт, который может обеспечить сбалансированный кайф, стимулицию ума и расслабление тела.
Fruity Pebbles, также известный как Fruity Pebbles OG и Fruity OG – это гибридный сорт с доминирующей индикой, созданный компанией Alien Genetics в 2006 году. Этот гибрид использует генетику Green Ribbon, Granddaddy Purple и Tahoe Alien для создания ягодного аромата. Он оказывает сильное эйфорическое действие, поднимает настроение при стрессе и способствует засыпанию у людей, страдающих бессонницей. Его вкус лесных ягод и молока со злаками, несомненно, перенесет вас в старые добрые времена.
Passion Fruit is a powerful sativa that is best known for its amazing smell and taste. As you might guess from its passion fruit pedigree, it will give you lots of sweet citrus and a nice floral note to balance it all out. The tropical aromas will make you wish you were sitting on the beach sipping a pina colada during the summer. When it comes to the effects, this strain will give you an epic feeling of euphoria and the desire to raid the pantry for fun stuff. Be sure to bring snacks! For pitmasters, this is the perfect strain for outdoor cooking. Passion Fruit is perfect for a long day of BBQs and yard games with friends and family.
https://secretvape.shop/
best online canadian pharmacy: USACanadaPharm – my canadian pharmacy
https://usacanadapharm.shop/# prescription drugs canada buy online
https://usacanadapharm.com/# usa canada pharm
canadian 24 hour pharmacy: thecanadianpharmacy – legal to buy prescription drugs from canada
USACanadaPharm: canadian pharmacy ed medications – canadian pharmacy prices
Axolotl problems
As Mexico City grew and became more industrialized, the need for water brought pumps and pipes to the lake, and eventually, “it was like a bad, smelly pond with rotten water,” Zambrano said. “All of our aquatic animals suffer with bad water quality, but amphibians suffer more because they have to breathe with the skin.”
жесткий анальный секс
To add to the axolotls’ problems, invasive fish species such as carp and tilapia were introduced to the lake, where they feed on axolotl eggs. And a 1985 earthquake in Mexico City displaced thousands of people, who found new homes in the area around the lake, further contributing to the destruction of the axolotls’ habitat.
These combined threats have devastated axolotl populations. According to the International Union for Conservation of Nature, there are fewer than 100 adult axolotls left in the wild. The species is considered critically endangered.
While the wild axolotls of Lake Xochimilco have dwindled to near-extinction, countless axolotls have been bred for scientific laboratories and the pet trade. “The axolotl essentially helped establish the field of experimental zoology,” Voss said.
In 1864, a French army officer brought live axolotls back to Europe, where scientists were surprised to learn that the seemingly juvenile aquatic salamanders were capable of reproduction. Since then, scientists around the world have studied axolotls and their DNA to learn about the salamanders’ unusual metamorphosis (or lack thereof) as well as their ability to regrow injured body parts.
In addition to their role in labs, axolotls have become popular in the exotic pet trade (though they are illegal to own in California, Maine, New Jersey and Washington, DC). However, the axolotls you might find at a pet shop are different from their wild relatives in Lake Xochimilco. Most wild axolotls are a dark grayish brown. The famous pink axolotls, as well as other color variants such as white, blue, yellow and black, are genetic anomalies that are rare in the wild but selectively bred for in the pet trade.
What’s more, “most of the animals in the pet trade have a very small genetic variance,” Zambrano said. Pet axolotls tend to be inbred and lack the wide flow of different genes that makes up a healthy population in the wild. That means that the axolotl extinction crisis can’t simply be solved by dumping pet axolotls into Lake Xochimilco. (Plus, the pet axolotls likely wouldn’t fare well with the poor habitat conditions in the lake.)
Fame and misfortune
The difficulties that axolotls face in the wild are almost diametrically opposed to the fame they’ve found in recent years. Axolotls have captured the human imagination for centuries, as evidenced by their roles in Aztec religion and stories, but the early 21st century seems to be a high point for them. An axolotl graces the 50 peso bill. There are axolotl-inspired Pokemon, and Reddit commenters have noted that the character Toothless from the “How to Train Your Dragon” movie series is distinctly axolotl-like.
The introduction of axolotls to Minecraft in 2021 neatly mapped onto an uptick in Google searches for the animals, and social media makes it easy for people to gain access to photos and videos of the salamanders, particularly the photogenic pink ones often kept as pets.
The axolotl pet trade probably doesn’t directly harm the wild populations since wild salamanders aren’t being poached or taken from Lake Xochimilco. However, Zambrano said, axolotls’ ubiquity in pop culture and pet stores might make people assume that because axolotls “live in all the tanks around the world, they are not in danger.”
Why axolotls seem to be everywhere — except in the one lake they call home
анальный секс первые
Scientist Dr. Randal Voss gets the occasional reminder that he’s working with a kind of superstar. When he does outreach events with his laboratory, he encounters people who are keen to meet his research subjects: aquatic salamanders called axolotls.
The amphibians’ fans tell Voss that they know the animals from the internet, or from caricatures or stuffed animals, exclaiming, “‘They’re so adorable, we love them,’” said Voss, a professor of neuroscience at the University of Kentucky College of Medicine. “People are drawn to them.”
Take one look at an axolotl, and it’s easy to see why it’s so popular. With their wide eyes, upturned mouths and pastel pink coloring, axolotls look cheerful and vaguely Muppet-like.
They’ve skyrocketed in pop culture fame, in part thanks to the addition of axolotls to the video game Minecraft in 2021. These unusual salamanders are now found everywhere from Girl Scout patches to hot water bottles. But there’s more to axolotls than meets the eye: Their story is one of scientific discovery, exploitation of the natural world, and the work to rebuild humans’ connection with nature.
A scientific mystery
Axolotl is a word from Nahuatl, the Indigenous Mexican language spoken by the Aztecs and an estimated 1.5 million people today. The animals are named for the Aztec god Xolotl, who was said to transform into a salamander. The original Nahuatl pronunciation is “AH-show-LOAT”; in English, “ACK-suh-LAHT-uhl” is commonly used.
Axolotls are members of a class of animals called amphibians, which also includes frogs. Amphibians lay their jelly-like eggs in water, and the eggs hatch into water-dwelling larval states. (In frogs, these larvae are called tadpoles.)
Most amphibians, once they reach adulthood, are able to move to land. Since they breathe, in part, by absorbing oxygen through their moist skin, they tend to stay near water.
Axolotls, however, never complete the metamorphosis to a land-dwelling adult form and spend their whole lives in the water.
“They maintain their juvenile look throughout the course of their life,” Voss said. “They’re teenagers, at least in appearance, until they die.”
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:ремонт бытовой техники в мск
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
USACanadaPharm: canadian pharmacy prices – buy drugs from canada
http://usacanadapharm.com/# usa canada pharm
warfarin pill – coumadin pills buy cozaar 50mg online
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:ремонт крупногабаритной техники в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
https://vk.com/wall-229186821_26
northern pharmacy canada canadian online pharmacy USACanadaPharm
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:ремонт крупногабаритной техники в москве
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
safe online pharmacies in canada: canada drugs online – usa canada pharm
http://usacanadapharm.com/# canadian pharmacy no scripts
Перейти на сайт водкабет
нажмите здесь vodkabet водка казино
usa canada pharm: online pharmacy canada – is canadian pharmacy legit
canadian pharmacy 24h com: canadian pharmacy king reviews – canadian pharmacy store
посмотреть на этом сайте зеркало vodkabet
USACanadaPharm: USACanadaPharm – USACanadaPharm
Hình ảnh tạo ra từ thiswojakdoesnotexist.com không đạt chất lượng mong muốn
интернет vodkabet водка казино
usa canada pharm: USACanadaPharm – canadian pharmacy sarasota