Sanket
Sanket

Reputation: 393

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

I have this 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>

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

    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);
       }
     }
    }

I get the Following results:

    Results
    Results

I also want root elements attribute :

     SchemaVersion="1.0" SchemaType="Results" GroupId="-12345" 
     xmlns="http://xyz"  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"

Upvotes: 2

Views: 6494

Answers (4)

Sumit Pandit
Sumit Pandit

Reputation: 1

public static void executeXMLToCSV() {
    File fXmlFile = new File(fileLocation);
    List<String> recordIndexCSVList = new ArrayList<String>();
    String recordIndexCSV = "";

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = null;
        try {
            doc = dBuilder.parse(fXmlFile);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        doc.getDocumentElement().normalize();
        NodeList rootsite = doc.getElementsByTagName("sites");
        Node rootsiteNode = rootsite.item(0);
        NodeList sites = rootsiteNode.getChildNodes();
        for (int siteCtr = 0; siteCtr < sites.getLength(); siteCtr++) {
            Node siteNode = sites.item(siteCtr);
            System.out.println("\nCurrent Element :"
                    + siteNode.getNodeName());
            if (siteNode.getNodeType() == Node.ELEMENT_NODE
                    && "site".equalsIgnoreCase(siteNode.getNodeName())) {
                Element eElement = (Element) siteNode;
                String siteId = eElement.getAttribute("id");
                String siteName = eElement.getAttribute("name");
                System.out.println("Staff id : " + siteId);
                System.out.println("Staff name : " + siteName);

                NodeList categories = siteNode.getChildNodes();
                for (int categoryCtr = 0; categoryCtr < categories
                        .getLength(); categoryCtr++) {
                    Node categoryNode = categories.item(categoryCtr);
                    System.out.println("\nCurrent Element :"
                            + categoryNode.getNodeName());
                    Element cElement = (Element) categoryNode;
                    String categoryId = cElement.getAttribute("id");
                    String categoryName = cElement.getAttribute("name");
                    System.out.println("categoryId : " + categoryId);
                    System.out.println("categoryName : " + categoryName);

                    NodeList fleets = categoryNode.getChildNodes();
                    for (int fleetCtr = 0; fleetCtr < fleets.getLength(); fleetCtr++) {
                        Node fleetNode = fleets.item(fleetCtr);
                        System.out.println("\nCurrent Element :"
                                + fleetNode.getNodeName());
                        Element fElement = (Element) fleetNode;
                        String fleetId = fElement.getAttribute("id");
                        String fleetName = fElement.getAttribute("name");
                        System.out.println("fleetId : " + fleetId);
                        System.out.println("fleetName : " + fleetName);

                        NodeList fleetChilds = fleetNode.getChildNodes();
                        for (int fleetChildCtr = 0; fleetChildCtr < fleetChilds
                                .getLength(); fleetChildCtr++) {
                            Node fleetChild = fleetChilds
                                    .item(fleetChildCtr);
                            if ("assets".equalsIgnoreCase(fleetChild
                                    .getNodeName())) {
                                NodeList assets = fleetChild
                                        .getChildNodes();
                                for (int assetCtr = 0; assetCtr < assets
                                        .getLength(); assetCtr++) {
                                    Node asset = assets.item(assetCtr);
                                    Element aElement = (Element) asset;
                                    String assetId = aElement
                                            .getAttribute("id");
                                    System.out.println("assetId : "
                                            + assetId);
                                    /*
                                     * Finally prepare a list of csv
                                     * strings... after this loop iterate
                                     * the list and prepare the final string
                                     * by concanating all.
                                     */
                                    String recordIndexCSV_index = siteId
                                            + "_" + categoryId + "_"
                                            + fleetId + "_" + assetId;
                                    String recordIndexCSVString = recordIndexCSV_index
                                            + delimeter
                                            + siteId
                                            + delimeter
                                            + categoryId
                                            + delimeter
                                            + fleetId
                                            + delimeter + assetId;
                                    recordIndexCSVList
                                            .add(recordIndexCSVString);
                                }
                            }
                        }
                    }
                }
            }
        }

        for (String recordIndexCSVString : recordIndexCSVList) {
            if ("".equals(recordIndexCSV)) {
                recordIndexCSV = recordIndexCSV + recordIndexCSVString;
            } else {
                recordIndexCSV = recordIndexCSV + seperator
                        + recordIndexCSVString;
            }
        }
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167516

Don and Jörn have already shown you how to access the attribute nodes in the DOM tree; as you have asked to use XPath to access them I will show an alternative, you could simply use the the XPath expression /*/@* to access the attribute nodes of the root element in the XPath data model. Note however that the namespace declarations are not attribute nodes in the XPath data model so that path will only find the attributes SchemaVersion="1.0" SchemaType="Results" GroupId="-12345". So based on your wanted result you are better off to use the DOM getAttributes instead of XPath.

Upvotes: 0

Don Roby
Don Roby

Reputation: 41137

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("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());
            NamedNodeMap attributes = nodes.item(0).getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.println(attributes.item(i));
            }

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

Upvotes: 1

J&#246;rn Horstmann
J&#246;rn Horstmann

Reputation: 34014

The Node class has a getAttributes method that should give you what you need:

NamedNodeMap attributes = nodes.item(0).getAttributes();
for (int i=0, len=attributes.getLenght(); i<len; i++) {
   Attr attr = (Attr)attributes.item(i);
   System.out.println(attr.getName() + "=" + attr.getValue());
}

Upvotes: 3

Related Questions