工作中遇到一个导出xml文件的需求,首次接触使用Java生成并导出xml,觉得比导出Excel方便多了,记录一下,方便后续使用。
Java中生成并导出xml文件十分简单,总体步骤分为:
1.定义导出路径
2.创建文档并给文档赋值
3.在指定路径下生成创建的文件
直接上代码:
定义导出路径
String filePath = "E:/"
创建文档并给文档赋值
生成xml的核心在此,我在这里写了3层作为示范,可以根据书写风格看出:
1.下级节点的创建是在父节点后添加.addElement方法。
2.节点内容使用.addAttribute来添加。
3…addAttribute方法源码中是
Element addAttribute(String var1, String var2);
var1视作key,可写死,var2视作value由自己动态填充
写起来行数虽多,但无需每行描述,可以当做一个工具包来使用,代码如下:
Document document = DocumentHelper.createDocument();
Element root = document.addElement("这是最外层标题");
root.addAttribute("Project", "1");
root.addAttribute("GenerateSys", "1");
root.addAttribute("Mac", "1");
Element topElement = root.addElement("这是第二层标题");
topElement.addAttribute("OrgCode", "2");
topElement.addAttribute("OrgStandardCode", "2");
topElement.addAttribute("OrgName", "2");
topElement.addAttribute("Address", "2");
Element areaElement = topElement.addElement("这是第三层标题");
areaElement.addAttribute("OrgCode", "2");
areaElement.addAttribute("OrgStandardCode", "3");
areaElement.addAttribute("OrgName", "3");
areaElement.addAttribute("Address", "3");
areaElement.addAttribute("OrgLevel", "3");
Document doc = updateMacAttributes(document);
generateXmlFiles(doc, filePath, "生成xml样例.xml"); //传入文档内容,指定地址,文档自定义名称,由此方法最终实现输出
}
在指定路径下生成xml文件
这用到上面写出的两个方法,也是可以当做工具包来使用,完全不用修改:
private static boolean generateXmlFiles(Document document, String path, String fileName) {
File filePath = new File(path);
if (!filePath.exists()) {
filePath.mkdirs();
}
String absoluteFileName = path + File.separator + fileName;
try {
FileOutputStream fos = new FileOutputStream(absoluteFileName);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(fos, format);
writer.write(document);
writer.close();
fos.close();
return new File(absoluteFileName).exists();
} catch (Exception e) {
e.printStackTrace();
log.error("生成xml文件失败,文件名={},错误信息={}", absoluteFileName, e);
throw new ServiceException("生成xml文件失败");
}
}
private static Document updateMacAttributes(Document xmlDocument) {
// 计算xml文档除了xml节点以及mac、xmlns属性值外所有信息的hash值
String macStr = XmlUtil.GetAllValues(xmlDocument);
Element rootElement = xmlDocument.getRootElement();
Attribute attribute = rootElement.attribute("Mac");
attribute.setText(macStr);
return xmlDocument;
}
上述拆开说明后,再贴一副完整代码**,可以直接拷贝下来使用,直接运行即可:**
public static void main(String[] args) {
String filePath = "E:/";
Document document = DocumentHelper.createDocument();
Element root = document.addElement("这是最外层标题");
root.addAttribute("Project", "1");
root.addAttribute("GenerateSys", "1");
root.addAttribute("Mac", "1");
Element topElement = root.addElement("这是第二层标题");
topElement.addAttribute("OrgCode", "2");
topElement.addAttribute("OrgStandardCode", "2");
topElement.addAttribute("OrgName", "2");
topElement.addAttribute("Address", "2");
Element areaElement = topElement.addElement("这是第三层标题");
areaElement.addAttribute("OrgCode", "2");
areaElement.addAttribute("OrgStandardCode", "3");
areaElement.addAttribute("OrgName", "3");
areaElement.addAttribute("Address", "3");
areaElement.addAttribute("OrgLevel", "3");
Document doc = updateMacAttributes(document);
generateXmlFiles(doc, filePath, "生成xml样例.xml");
}
private static boolean generateXmlFiles(Document document, String path, String fileName) {
File filePath = new File(path);
if (!filePath.exists()) {
filePath.mkdirs();
}
String absoluteFileName = path + File.separator + fileName;
try {
FileOutputStream fos = new FileOutputStream(absoluteFileName);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(fos, format);
writer.write(document);
writer.close();
fos.close();
return new File(absoluteFileName).exists();
} catch (Exception e) {
e.printStackTrace();
log.error("生成机考xml文件失败,文件名={},错误信息={}", absoluteFileName, e);
throw new ServiceException("生成机考xml文件失败");
}
}
private static Document updateMacAttributes(Document xmlDocument) {
// 计算xml文档除了xml节点以及mac、xmlns属性值外所有信息的hash值
String macStr = XmlUtil.GetAllValues(xmlDocument);
Element rootElement = xmlDocument.getRootElement();
Attribute attribute = rootElement.attribute("Mac");
attribute.setText(macStr);
return xmlDocument;
}
运行后的效果,在E盘中可以看到,如图:
其中生成xml的XmlUtil这个工具类补充下:
```java
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
public class XmlUtil {
private static String XmlNodeName = "xml";
private static String MacAttribute = "Mac";
private static String xmlNameSpacePrefix = "xmlns";
public static String GetAllValues(Document xmlDocument) {
ArrayList<String> valueList = new ArrayList<String>();
Element nodeElement = xmlDocument.getRootElement();
RecursionGetValues(nodeElement, valueList);
Collections.sort(valueList);
// /获取所有的字符串的组合
StringBuilder builder = new StringBuilder();
String value = "";
for (int i = 0; i < valueList.size(); i++) {
value = valueList.get(i) ;
builder.append(value.trim()) ;
}
String Mac = HashBase64(builder.toString());
return Mac;
}
private static void RecursionGetValues(Element node,
ArrayList<String> valueList) {
// /如果是xml节点不做计算,xml节点为xml规范版本的信息不做计算
if (node.getName() != null && node.getName().toLowerCase() == XmlNodeName) {
return;
}
if (node.attributes() != null) {
for (Iterator it = node.attributeIterator(); it.hasNext();) {
Attribute attribute = (Attribute) it.next();
if (!attribute.getName().equals(MacAttribute)
&& !attribute.getName().equals(xmlNameSpacePrefix)) {
valueList.add(attribute.getText());
}
}
}
// 递归获取值
for (Iterator it = node.elementIterator(); it.hasNext();) {
Element childNode = (Element) it.next();
RecursionGetValues(childNode, valueList);
}
if (node.getText() != null) {
valueList.add(node.getText());
}
}
public static String HashBase64(String str) {
String ret = "";
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
try {
// Hash算法
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(str.getBytes("utf-8"));
byte[] sha1 = sha.digest();
int j = sha1.length;
char strSha[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = sha1[i];
strSha[k++] = hexDigits[byte0 >>> 4 & 0xf];
strSha[k++] = hexDigits[byte0 & 0xf];
}
ret = String.valueOf(strSha);
} catch (Exception e) {
System.out.print(e.getMessage());
}
return ret;
}
}
一个简单的xml文件实战记录到此结束了,简单记一下思路以备后面回想,有问题欢迎指出。