/**
* 读取原xml文件转换为string类型
*/
String content=XMLUtil.readFileToString(c:\12345.xml);
/**
*写正则定义xml中所有包含systemDiffCode的值进行定义
* \w 表示匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。
*/
String regEx="systemDiffCode=\"(\\w+?)\"";
Pattern pat=Pattern.compile(regEx);
Matcher mat=pat.matcher(content);
content=mat.replaceAll("systemDiffCode=\""+'10'+"\"");
/**
*写正则定义xml中所有包含systemCode的值进行定义
*/
regEx="systemCode=\"(\\w+?)\"";
pat=Pattern.compile(regEx);
mat=pat.matcher(content);
content=mat.replaceAll("systemCode=\""+'20'+"\"");
System.out.print(content);
/**
* 写xml文件,形成新的xml文件
*/
XMLUtil.WriteStringToXMLFile(content, "c:\\123.xml");
上面content=mat.replaceAll("infoCode=\""+'10'+"\"");content=mat.replaceAll("infoCode=\""+'20'+"\"");
10和20就是要替换的值,根据需要可以自行修改想要的值。
XMLUtil工具类:
package com.huige.utils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XMLUtil {
private static final Log logger = LogFactory.getLog(XMLUtil.class);
private static final String XML_LINE_BREAK = "
";
public static final String SUFFIX_XML = ".xml";
private static boolean isExisDocType(String sourceXML) {
if (sourceXML.indexOf("<!DOCTYPE") > 0) return true;
return false;
}
public static String getXMLDoctypeToDoc(String sourceXML) {
String doctype = "";
if (sourceXML.indexOf("<!DOCTYPE") != -1) {
doctype += sourceXML.substring(sourceXML.indexOf("<!DOCTYPE") + "<!DOCTYPE".length(), sourceXML.indexOf("]>") + 1);
}
return doctype;
}
/**
* 解析带有doctype和不带有doctype定义的XML内容
*
* @param xmlStr
* @return
*/
public static Document parseStringOfDocTypeToDocument(String xmlStr) {
try {
SAXReader sax = new SAXReader();
sax.setValidation(false);
if (isExisDocType(xmlStr)) sax.setEntityResolver(new CopyrightTesolver());
Document document = sax.read(new ByteArrayInputStream(xmlStr.getBytes("utf-8")));
String doctypeString = getXMLDoctypeToDoc(xmlStr);
if (null != document.getDocType()) document.getDocType().setElementName(doctypeString);
return document;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Document parseStringToDocument(String xmlStr) {
try {
Document document = DocumentHelper.parseText(xmlStr);
return document;
} catch (Exception e) {
logger.error("XMLUtil:parseStringToDocument:" + xmlStr);
e.printStackTrace();
return null;
}
}
/**
* String Element
*
* @param xmlStr -
* xml String
* @return Element
*/
public static Element parseStringToElement(String xmlStr) {
try {
Document document = parseStringToDocument(xmlStr);
if (document != null) {
return document.getRootElement();
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Element String
*
* @param element -
* Element
* @return java.lang.String
*/
public static String parseElementToString(Element element) {
return element.asXML();
}
/**
* Document String
*
* @param - document
* @return java.lang.String
*/
public static String parseDocumentToString(Document document) {
return document.asXML();
}
/**
*
*
* @param filePath
* @return javax.swing.text.Document
* @throws DocumentException
*/
public static String readFileToString(String filePath) {
StringBuffer buf;
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8");
BufferedReader read = new BufferedReader(isr);
buf = new StringBuffer();
while (read.ready())
buf.append((char) read.read());
read.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return buf.toString();
}
/**
* @param @param filePath 设定文件
* @return void 返回类型
* @throws
* @Title: addXMLDoctype
* @Description: 为xml添加Doctype
*/
public static String addXMLDoctype(String sourceXML, String filePath) {
String xml = "";
Document document = null;
SAXReader reader = new SAXReader();
reader.setEncoding("UTF-8");
Writer wr = null;
try {
File xmlFile = new File(filePath);
document = reader.read(xmlFile);
wr = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
xml = getXMLDoctype(sourceXML) + document.getRootElement().asXML();
wr.write(xml);
wr.flush();
wr.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
/**
* @return 设定文件
* @return String 返回类型
* @throws
* @Title: getXMLDoctype
* @Description: 获取xml的Doctype
*/
public static String getXMLDoctype(String sourceXML) {
String doctype = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
if (sourceXML.indexOf("<!DOCTYPE") != -1) {
doctype += sourceXML.substring(sourceXML.indexOf("<!DOCTYPE"), sourceXML.indexOf("]>") + 2);
}
return doctype;
}
public static String readInToString(InputStream is) {
StringBuffer buf;
BufferedReader breader;
try {
breader = new BufferedReader(new InputStreamReader(is));
buf = new StringBuffer();
while (breader.ready())
buf.append((char) breader.read());
breader.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return buf.toString();
}
/**
* Element
*
* @param
* @param filePath -
*
* @return boolean
*/
public static Boolean WriteDocumentToFile(Document document, String filePath, String fileName) {
//设置生成xml的格式
OutputFormat format = OutputFormat.createPrettyPrint();
//设置编码格式
format.setEncoding("UTF-8");
try {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
//生成XML文件
File file = new File(filePath + fileName + SUFFIX_XML);
XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
//设置是否转义,默认使用转义字符
writer.setEscapeText(false);
writer.write(document);
writer.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
*
* @param parentElement -
*
* @param attribute -
* document
* @return javax.swing.text.Element
*/
@SuppressWarnings("unchecked")
public List<Element> getElementByAttribute(Element parentElement,
Attribute attribute) {
List<Element> nodeList = parentElement.elements();
List<Element> returnList = new ArrayList();
for (Element childNode : nodeList) {
if (childNode.attributeValue(attribute.getName()).equals(
attribute.getValue())) {
returnList.add(childNode);
}
}
return null;
}
/**
*
*
* @param parentElement -
*
* @param - Element??tagName
* @return javax.swing.text.Element
*/
public List<Element> getElementByTagName(Element parentElement,
String tagName) {
List<Element> list = parentElement.elements(tagName);
return list;
}
/**
*Element
*
* @param -
* @param element1 -Element
* @param element2 -Element
* @return boolean
*/
public boolean getElementByTagName(Element element1, Element element2) {
if (element1.asXML().equals(element2.asXML())) {
return true;
} else {
return false;
}
}
/**
*
*
*
* @param fileName
* @return Document
* @throws MalformedURLException
* @throws DocumentException
*/
public static Document read(String fileName) throws MalformedURLException,
DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(new File(fileName));
return document;
}
/**
* Root
*
* @param
* @return
*/
public Element getRootElement(Document doc) {
return doc.getRootElement();
}
/**
*
*
* @param -XML
* @param id-XML ID
* @param elementPath --"ui/UiFormat" "result/datasets"
* @return
*/
public static StringBuffer getSContent(String xml, String id,
String elementPath) {
StringBuffer sContent = new StringBuffer("");
Document doc = null;
doc = parseStringToDocument(xml);
Element temp = null;
temp = (Element) doc.selectSingleNode(elementPath + "[@id=" + id + "]");
Iterator iterator = temp.elementIterator();
while (iterator.hasNext()) {
Element element1 = (Element) iterator.next();
String value = parseElementToString(element1);
sContent.append(value);
}
return sContent;
}
/**
*
*
* @param xml
* @param id
* @param elementPath??????
* @return type?????
* @throws Throwable
*/
public static String getTypeFromContent(String xml, String id,
String elementPath) throws Throwable {
String value = null;
Element foo = null;
try {
Document doc = null;
doc = parseStringToDocument(xml);
Element temp = null;
temp = (Element) doc.selectSingleNode(elementPath + "[@id=" + id
+ "]");
Iterator iterator = temp.elementIterator();
Element element1 = (Element) iterator.next();
value = parseElementToString(element1);
foo = parseStringToElement(value);
} catch (Exception e) {
e.printStackTrace();
logger.info("IDtype");
throw e;
}
return foo.elementText("type");
}
/**
* @param xml
* @param elementPath
* @return
* @throws DocumentException
*/
public static String getNodeText(String xml, String elementPath)
throws DocumentException {
Element temp = null;
Document doc = null;
try {
doc = XMLUtil.parseStringToDocument(xml);
temp = (Element) doc.selectSingleNode(elementPath);
} catch (Exception e) {
e.printStackTrace();
logger.info("!");
}
return temp.getText();
}
/**
*
*
* @param xml
* @param id
* @param elementPath
* @return
* @throws DocumentException
*/
public static String getNodeTextById(String xml, String id,
String elementPath, String s) throws DocumentException {
String value = null;
Element foo = null;
Document doc = null;
doc = parseStringToDocument(xml);
Element temp = null;
temp = (Element) doc.selectSingleNode(elementPath + "[@id=" + id + "]");
Iterator iterator = temp.elementIterator();
Element element1 = (Element) iterator.next();
value = parseElementToString(element1);
foo = parseStringToElement(value);
return foo.elementText(s);
}
public static boolean WriteStringToXMLFile(String xmlStr, String filePath) {
try {
System.out.println("--------------------------" + filePath);
Document document = DocumentHelper.parseText(xmlStr);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
format.setNewLineAfterDeclaration(false);
//format.setSuppressDeclaration(true);
format.setIndent(true);
//format.setNewlines(true);
org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(
new FileOutputStream(filePath), format);
xmlWriter.write(document);
xmlWriter.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
*
* @param xml <row><key>2008-01-07 13:32:17</key><value>0</value></row>
* @param s key
* @return java.lang.string
*/
public static String getNodeTextByTag(String xml, String s) {
Element temp = null;
temp = (Element) XMLUtil.parseStringToElement(xml);
return temp.elementText(s);
}
/**
* @param @return
* @return Document
* @throws
* @Title: createNewDocument
* @Description: ??Document??
*/
public static Document createNewDocument() {
Document doc = DocumentHelper.createDocument();
return doc;
}
/**
* @param @param doc
* @param @param path
* @param @throws IOException
* @return void
* @throws
* @Title: writeXML
* @Description: 写入XML文件
*/
public static void writeXML(Document doc, String path) throws IOException {
try {
WriteStringToUTF8File(doc.asXML(), path);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void WriteStringToUTF8File(String str, String filePath) throws Exception {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
fos = new FileOutputStream(filePath);
osw = new OutputStreamWriter(fos, "utf-8");
osw.write(str);
osw.flush();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
if (osw != null) {
osw.close();
}
}
}
public static boolean WriteDocUmentToFile(Document document, String filePath) {
try {
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
format.setNewLineAfterDeclaration(true);
//format.setSuppressDeclaration(true);
format.setIndent(true);
//format.setNewlines(true);
format.setTrimText(true);
org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(
new FileOutputStream(filePath),format);
xmlWriter.write(document);
xmlWriter.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}