# java.xml 範例 參數紀錄在 XML 檔案中, Legacy code 的做法是使用 Dom4j 解析 xml 檔案,jaxen 描述節點路徑。 這次使用 Java 11 中內建的 Java.xml 模組操作 xml 。 Demo.xml 資料結構: ```xml= <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xml> <properties> <propertie name="PedroLogin"> <item key="USER" value="Pedro" /> <item key="URL" value="https://codetest.Pedro.tw:444/index" /> </propertie> <propertie name="PedroProg"> <item key="CheckOut_Path" value="C:\temp\pedro" /> <item key="CheckIn_DEL" value="false" /> </propertie> </properties> ``` ## 讀取 xml 讀取資料並存入 Hashmap 中。 ``` java= import org.w3c.dom.* ...(略) // 取設定檔屬性Map public static HashMap<String, String> XMLMap(String strType) throws Exception { HashMap<String, String> mapXML = new HashMap<String, String>(); // 取得程式當前路徑 String strDir = System.getProperty("user.dir"); // 開啟盪案 File file = new File(strDir + "\\properties.xml"); // 建立工廠 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 建立解析器 DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); // 建立 Xpath XPath xPath = XPathFactory.newInstance().newXPath(); // 設定節點 Xpath String expression = "/properties/propertie[@name='" + strType + "']/item"; // 路徑 // 取得結點資料 NodeList nodelist = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); // 讀取properties.xml放入MAP for (int i = 0; i < nodelist.getLength(); i++) { Node node = nodelist.item(i); Element element = (Element) node; mapXML.put(element.getAttribute("key"), element.getAttribute("value")); } return mapXML; } ``` ## 寫入 xml ```java= private static void WriteSomthing() throws Exception { // 度取資料 String strDir = System.getProperty("user.dir"); File file = new File(strDir + "\\properties.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // 建立解析器 Document doc = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/properties/propertie[@name='Login']/item[@key='USER']"; // 路徑 NodeList node = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); // 取出 element Element element = (Element) node.item(0); // 寫入檔案 // 修改參數 element.setAttribute("value", "PedroTest"); // 建立轉換器 TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); // source 不一定是整份檔案,只要 xml 格式正確可以是子階樹結構 DOMSource source = new DOMSource(doc); // 寫入的檔案 FileWriter writer = new FileWriter(new File(file.getPath())); // 可以用 java.io.Writer or java.io.OutputStream 來創建 StreamResult. StreamResult result = new StreamResult(writer); // 寫入原來的檔案 transformer.transform(source, result); // // 寫入到其他路徑 // StreamResult resultToFile = new StreamResult(new File("C:/temp/XMLFromPathValue.xml")); // transformer.transform(source, resultToFile); } ``` ## 操作 其中 Element element = (Element) node; 會產生 ```java= java.lang.ClassCastException: com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList incompatible with org.w3c.dom.Element ``` 此階段的 NodeList 是使用 DTMNodeList 無法給 org.w3c.dom.Element 使用, 將此 list 中的物件取出才可以正常操作,故修改成; Element element = (Element) node.item(0); ###### tags: `Java`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up