Get Attributes of the Root element in XML using xpath query expression in Java

monas

New Member
I have this XML \[code\] <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>\[/code\]And i have this code in Java which parses the above xml. I want to get the attributes of the root element in xml using xpath query. I am able to retrieve the value of root element but not the attributes. Note: I dont know the attribute names in this case otherwise i could have directly accessed those attributes\[code\] 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); } } }\[/code\]I get the Following results:\[code\] Results Results\[/code\]I also want root elements attribute : \[code\] SchemaVersion="1.0" SchemaType="Results" GroupId="-12345" xmlns="http://xyz" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"\[/code\]
 
Back
Top