使用dom4j 解析, 操作XML
首先說明一下一下事例的需求:
1. 找到並解析xml 檔案
2. 解析xml 檔案得到指定值
3. 然後生成一個新的xml 並把值寫入新的xml: 新的xml 檔案以'.bak' 結尾做為識別.
解析xml :
package com.inetpsa.replace;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlParser {
public static void main(String[] args) {
XmlParser parser = new XmlParser();
ChangeXmlContent changeXmlContent = new ChangeXmlContent();
String filePath = "junit/com/inetpsa/replace/config-file.xml";
Document configXmlDocument = null;
Element root = null;
List<Element> projectNameElements = null;
List<Element> projectListFileElements = null;
List<Element> projectFileListElements = null;
String projectName = "";
String xmlFile = "";
String outputXmlFile = "";
String processXmlFile = "";
try {
configXmlDocument = parser.getDocument(filePath);
root = configXmlDocument.getRootElement();
projectNameElements = root.elements("project");
for (Element element : projectNameElements) {
projectName = "../" + element.elementText("name");
// get all the file under this node;
projectListFileElements = element.elements("list-file");
for (Element fileElement : projectListFileElements) {
projectFileListElements = fileElement.elements("filePath");
for (Element fileListElement : projectFileListElements) {
xmlFile = fileListElement.getText().trim();
processXmlFile = projectName + xmlFile;
outputXmlFile = processXmlFile + ".bak";
System.out.println("xml file list : " + processXmlFile);
changeXmlContent.processXml(processXmlFile, outputXmlFile);
}
}
}
System.out.println("All xml file generated ended!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public Document getDocument(String filePath) throws Exception {
File xmlFile = new File(filePath);
SAXReader sr = new SAXReader();
Document document = sr.read(filePath);
return document;
}
}
替換xml 內容:
package com.inetpsa.replace;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class ChangeXmlContent {
public void processXml(String filePath, String saveFilePath) throws Exception {
File xmlFile = new File(filePath);
File saveFile = new File(saveFilePath);
// Read the file By BufferedReader object
FileReader reader = new FileReader(xmlFile);
BufferedReader bufferReader = new BufferedReader(reader);
FileWriter writer = new FileWriter(saveFile);
BufferedWriter bufferWriter = new BufferedWriter(writer);
String fileContent = "";
String exportContent = "";
String remoteException = "";
String[] strArray = null;
boolean isProcess;
boolean isLegalEndFlg = false;
int offset = 0;
int endXmlFlg = 0;
int endPoint = 0;
// Read the xml file and outpu the process result;
while ((fileContent = bufferReader.readLine()) != null) {
isProcess = false;
offset = fileContent.indexOf('<');
if (offset != -1) {
// find the move flag\
offset = offset + 1;
endXmlFlg = fileContent.lastIndexOf('/');
if (fileContent.startsWith("move", offset)) {
// find it successfully and legal format as following :
// <move nature="LLA" valeur="278" to="ALV_3151" remoteExecution="true" />
strArray = fileContent.split(" ");
for (int i = 0; i < strArray.length; i++) {
if (strArray[i].startsWith("remoteExecution", 0)) {
offset = strArray[i].lastIndexOf("\"");
endPoint = strArray[i].length() - offset;
remoteException = parseAttributeValue(strArray[i], endPoint);
if ("true".equals(remoteException)) {
isProcess = true;
isLegalEndFlg = true;
exportContent = parseMoveNode(fileContent, strArray, endXmlFlg);
}
}
}
if (!isProcess) {
exportContent = fileContent;
}
} else {
if (endXmlFlg != -1 && fileContent.startsWith("move", endXmlFlg + 1) && isLegalEndFlg == true) {
// Process the xml node as following :
// </move>
exportContent = processEndMoveFlag(fileContent, offset - 1);
isLegalEndFlg = false;
} else {
// other format type
exportContent = fileContent;
}
}
} else {
exportContent = fileContent;
}
bufferWriter.write(exportContent);
bufferWriter.flush();
bufferWriter.newLine();
}
System.out.println("Process the xml file ending!");
bufferReader.close();
bufferWriter.close();
reader.close();
writer.close();
bufferReader = null;
bufferWriter = null;
reader = null;
writer = null;
xmlFile = null;
saveFile = null;
}
/**
* Parses the 'Move' Flag and return the String content;
*
* @param content the content
* @return the string
*/
private String parseMoveNode(String fileContent, String[] content, int endFlg) {
// For particular Content of String array :
// content[0] : \t<move
// content[1] : nature="LLA"
// content[2] : valeur="251"
// content[3] : to="ALV_3133"
// content[4] : remoteExecution="true"
// content[5] : />
StringBuilder sb = new StringBuilder();
// parse the startpoint of 'move' node;
// initial the return String value
int pos = 0;
boolean flg = false;
// process the head of xml node 'move'
pos = fileContent.indexOf('<');
sb.append(fileContent.substring(0, pos));
sb.append("<messageweb_pour_appli contenu=\"--codeMessage::MOVE_ELEMENT");
// process the attribute 'nature';
addContent(content, sb, "nature", "--nature::");
// process the attribute 'valeur';
addContent(content, sb, "valeur", "--value::");
// process the attribute 'codeEncours';
flg = addContent(content, sb, "to", "--codeEncours::");
sb.append("--");
if (!flg) {
// process the attribute 'codeEncours'
addContent(content, sb, "from", "--codeEncours::");
sb.append("--");
}
// add the left part string and return it.
if (endFlg != -1) {
sb.append("\"/>");
} else {
sb.append("\">");
}
return sb.toString();
}
/**
* Adds the content into the StringBuilder object.
*
* @param content the content
* @param sb the StringBuilder
* @param attributeName the attribute name
* @param prefix the prefix
*/
private boolean addContent(String[] content, StringBuilder sb, String attributeName, String prefix) {
String valeur = "";
boolean isSuccess = false;
for (int i = 0; i < content.length; i++) {
if (content[i].startsWith(attributeName, 0)) {
sb.append(prefix);
valeur = parseAttributeValue(content[i], 1);
sb.append(valeur);
isSuccess = true;
break;
}
}
return isSuccess;
}
/**
* Parses the attribute value like the following : nature="LLA" valeur="251" to="ALV_3133"
*
* @param content the content
* @return the string
*/
private String parseAttributeValue(String content, int endPoint) {
String value = "";
int pos = 0;
pos = content.indexOf('=');
if (pos != -1) {
value = content.substring(pos + 2, content.length() - endPoint);
}
return value;
}
/**
* Process end Move flag </move>
*
* @param fileContent the file content
* @param offset the offset
* @return the string
*/
private String processEndMoveFlag(String fileContent, int offset) {
StringBuilder sb = new StringBuilder();
sb.append(fileContent.substring(0, offset));
sb.append("</messageweb_pour_appli>");
return sb.toString();
}
}
config-xml 檔案配置:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<project>
<name>pyrta</name>
<list-file>
<filePath>
/tester/03-MDA/enAttenteDeDev/SMDA_BlocageSP3.xml
</filePath>
<filePath>
/tester/03-MDA/SL/exception/SL_exception.xml
</filePath>
<filePath>
/tester/include/MDA_sature.xml
</filePath>
<filePath>
/tester/include/template/annulation_mission.xml
</filePath>
</list-file>
</project>
<project>
<name>pyrta</name>
<list-file>
<filePath>
/tester/include/MDA_sature.xml
</filePath>
<filePath>
/tester/include/template/annulation_mission.xml
</filePath>
</list-file>
</project>
</config>
run XmlParser -->
<move nature="LLA" valeur="278" to="ALV_3135" remoteExecution="true" />
<messageweb_pour_appli contenu="--codeMessage::MOVE_ELEMENT--nature::LLA--value::278--codeEncours::ALV_3135--" />
相關文章
- 使用Dom4j解析XML案例XML
- dom4j解析xmlXML
- Dom4j 操作 XMLXML
- Dom4j解析XML資料XML
- java的XML解析(DOM4J技術)JavaXML
- Java DOM4J 方式解析XML檔案JavaXML
- 用dom4j,解析xml 最好、最方便!XML
- 【菜鳥學Java】9:使用dom4j解析jdbc.xmlJavaJDBCXML
- DOM4J 解析 XML 之忽略轉義字元XML字元
- 用dom4j SAXReader解析xml檔案及字串XML字串
- Java解析XML彙總(DOM/SAX/JDOM/DOM4j/XPath)JavaXML
- dom4j 學習 -- 封裝dom4j工具類+如何使用dom4j解析封裝
- 使用jdom解析XMLXML
- java學習:使用dom4j讀寫xml檔案JavaXML
- 四種操作xml的方式: SAX, DOM, JDOM , DOM4J的比較XML
- dom4j遍歷巢狀xml巢狀XML
- Dom4j 讀寫XML簡介XML
- dom4j讀寫xml檔案XML
- java使用sax解析xmlJavaXML
- 關於dom4j對xml檔案實現增刪改創的操作XML
- dom4j 讀取網路的xmlXML
- 利用dom4j來生成xml檔案XML
- 使用jaxp解析器dom方式對xml節點進行操作XML
- Dom4j 讀 xml 時,遇到 xml 無效字元,報錯:An invalid XML characterXML字元
- 使用DocumentBuilderFactory解析XML淺談UIXML
- 使用 Java 解析XML檔案JavaXML
- python使用SAX解析xmlPythonXML
- 通過dom4j對xml文件的讀取操作工具類封裝XML封裝
- java中四種操作(DOM、SAX、JDOM、DOM4J)xml方式詳解與比較JavaXML
- Dom4j解析【開發中常用】
- Xml解析XML
- 使用PHP DOM-XML建立和解析XML檔案 (轉)PHPXML
- XML操作XML
- 操作XMLXML
- xml 操作XML
- JAVA-使用SAX解析XML資料JavaXML
- Android中XML的解析--使用PULLAndroidXML
- 使用Digester解析XML文件示例 (轉)XML