我有这个 XML
<Results SchemaVersion="1.0" SchemaType="Results" GroupId="-12345"
xmlns="http://xyz" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
<Attempt>
<Time>2007-03-30T15:58:15</Time>
<Message>This is some message</Message>
</Attempt>
<Attempt>
<Time>2007-03-30T15:59:45</Time>
<Message>This is some other message</Message>
</Attempt>
</Results>
我在Java中有这段代码,可以解析上面的xml。我想使用 xpath 查询获取 xml 中根元素的属性。我能够检索根元素的值,但不能检索属性。注意:在这种情况下我不知道属性名称,否则我可以直接访问这些属性
public class Try {
public static void main(String args[]){
try{
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("C:/Documents and Settings/tulans/workspace/WebServiceTool/src/main/resources/Input.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/*");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println(nodes.item(0).getLocalName());
System.out.println(nodes.item(0).getNodeName());
}catch(Exception e){
System.out.println(e);
}
}
}
我得到以下结果:
Results
Results
我还想要根元素属性:
SchemaVersion="1.0" SchemaType="Results" GroupId="-12345"
xmlns="http://xyz" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"