您的位置:首页 > 编程语言 > Java开发

使用dom4j 解析, 操作XML

2016-09-13 14:55 323 查看
首先说明一下一下事例的需求: 

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--" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  xml java