您好我有要求像解析XML,并得到所有子节点有节点<Employees>
和</Employees>
解析XML得到所有子节点和他们的数据使用Java XPATH
之间的数据我有XML这样的:
<?xml version="1.0"?>
<Employees>
<Employee emplid="1111" type="admin">
<firstname>test1</firstname>
<lastname>Watson</lastname>
<age>30</age>
<email>[email protected]</email>
</Employee>
<Employee emplid="2222" type="admin">
<firstname>Sherlock</firstname>
<lastname>Homes</lastname>
<age>32</age>
<email>[email protected]</email>
</Employee>
</Employees>
我需要一个像
<Employee emplid="1111" type="admin">
<firstname>test1</firstname>
<lastname>Watson</lastname>
<age>30</age>
<email>[email protected]</email>
</Employee>
<Employee emplid="2222" type="admin">
<firstname>Sherlock</firstname>
<lastname>Homes</lastname>
<age>32</age>
<email>[email protected]</email>
</Employee>
响应我曾尝试下面的代码
FileInputStream file = new FileInputStream(new File("E:\\test.xml"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("*************************");
String expression = "/Employees/*";
System.out.println(expression);
String email = xPath.compile(expression).evaluate(xmlDocument);
System.out.println(email);
,但我越来越喜欢
test1
Watson
30
[email protected]
回应,我已经使用表达喜欢/员工/ *,但它不工作
谁能帮我做这个?
的XPath表达式是正确的选择根元素的所有子元素。但是,要将节点序列化回一串标记,需要使用DOM Level 3 Load和Save API或默认转换器。 –
所以我们不能使用简单的xpath?如果你有任何工作代码可以分享? –
XPath 1.0和2.0不会序列化节点,不,在XPath 3.0中,您可以使用http://www.w3.org/TR/xpath-functions-30/#func-serialize,例如, '/ Employees/*/serialize(。)'得到一串字符串。但Oracle Java JRE不支持XPath 3.0,您使用的API不是专为XPath 2.0或3.0而设计的。 –