package com.huawei.cddevops;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class test {
private Map<String ,String> reportMap = new HashMap<String, String>();
private Node node;
public Map<String, String> getReportMap() {
return reportMap;
}
public void setReportMap(Map<String, String> reportMap) {
this.reportMap = reportMap;
}
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public static void main(String[] args) throws FileNotFoundException, DocumentException{
test t=new test();
t.xml("d://test.xml");
}
public void xml(String filePath) throws FileNotFoundException, DocumentException{
//判断重复时候不加载
SAXReader reader = new SAXReader();
InputStream inputStream = null;
File file = new File(filePath);
inputStream = new FileInputStream(file);
Document document = reader.read(inputStream);
List<Node> layerNodes = document.selectNodes("//layer");//获取xml根节点
if(layerNodes.size() > 0 ){
Node layerNode = layerNodes.get(0);//获取xml名为layer下面的一个节点
this.setNode(layerNode);
if(layerNode.selectSingleNode("./book")!=null){
System.out.println(this.getTextByNodeXpath(this.getNode(), "./book/textbook/@English"));//输出6
this.getTextByNodeXpath(this.getNode(), "./book/textbook/@Chinese");
this.getTextByNodeXpath(this.getNode(), "./book/textbook/@mathematics");
}
}
}
/**
* 根据Xpath表达式获取节点
* @param node
* @param xpath
* @return
*/
public static String getTextByNodeXpath(Node node,String xpath){
Node singNode = node.selectSingleNode(xpath);//获取节点
if(singNode==null) return null;
return singNode.getText();
}
public static JSON getJSONFromXml(String xmlString) {
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xmlString);
return json;
}
}
以下是名为test.xml文件的内容
<?xml version="1.0" encoding="UTF-8"?>
<cruisecontrol>
<layer name="test1">
<book>
<textbook English="6" Chinese="7" mathematics="9" />
</book>
</layer>
</cruisecontrol>