一、用xpath不能获取xml数据,是由于xml文件本身的约束限制。如:xmlns等
<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:mif="urn:hl7-org:v3/mif" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 ..\sdschemas\SDA.xsd">
解决方法:
替换掉了相关约束,只留下了xmlns:xsi属性,xpath提取数据成功。
二、常用XPATH解析
<?xml version="1.0" encoding="UTF-8"?>
<class>
<student>
<name>张三</name>
<sid>111111</sid>
</student>
<student id="stu1">
<name>李四</name>
<sid>222222</sid>
</student>
</class>
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Dom4jXpath {
public static void main(String[] args) throws Exception {
select();//查询所有name的值
//select2();//查询id=stu1的学生的name的值
}
//查询所有name的值
private static void select() throws Exception {
SAXReader saxReader=new SAXReader();
Document document=saxReader.read("src/1.xml");
List<Node>list=document.selectNodes("//name");
for(int i=0;i<list.size();i++)
System.out.println(list.get(i).getText());
}
//查询id=stu1的学生的name的值
private static void select2() throws Exception {
SAXReader saxReader=new SAXReader();
Document document=saxReader.read("src/1.xml");
Node node=document.selectSingleNode("//student[@id='stu1']/name");
System.out.println(node.getText());
}
}
已用示例
Map<String, String> result = new HashMap<>();
List<Node> nodes = document.selectNodes(
"//ClinicalDocument/component/structuredBody/component/section/entry/observation");
for (Node node : nodes) {
List<Node> nodeList = node.selectNodes("code[@displayName='主诉']");
if (nodeList.size() != 0) {
String value = node.selectSingleNode("value").getText();
result.put("主诉", value);
}
List<Node> nodeList2 = node.selectNodes("code[@displayName='现病史']");
if (nodeList2.size() != 0) {
String value = node.selectSingleNode("value").getText();
result.put("现病史", value);
}
List<Node> nodeList3 = node.selectNodes("code[@displayName='确定诊断-西医诊断名称']");
if (nodeList3.size() != 0) {
String value = node.selectSingleNode("value").getText();
result.put("诊断", value);
}
}