how to get the attribute value of an xml node using java

Viewed 123208

I've an xml which looks like this:

{ <xml><ep><source type="xml">...</source><source type="text">..</source></ep></xml>}

here i wanna retrieve the value of "source type" where type s an attribute.

I 'd tried like this,But its not working:

 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder builder = domFactory.newDocumentBuilder();
                    Document dDoc = builder.parse("D:/workspace1/ereader/src/main/webapp/configurations/config.xml");
                    System.out.println(dDoc);
                    XPath xPath = XPathFactory.newInstance().newXPath();
                    Node node = (Node) xPath.evaluate("//xml/source/@type/text()", dDoc, XPathConstants.NODE);
                    System.out.println(node);
                } catch (Exception e) {
                    e.printStackTrace();

i've tried this too :

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader("config.xml"));
            Document doc = builder.parse(is);

            NodeList nodeList = doc.getElementsByTagName("source");

            for (int i = 0; i < nodeList.getLength(); i++) {                
                Node node = nodeList.item(i);

                if (node.hasAttributes()) {
                    Attr attr = (Attr) node.getAttributes().getNamedItem("type");
                    if (attr != null) {
                        String attribute= attr.getValue();                      
                        System.out.println("attribute: " + attribute);                      
                    }
                }
            }

pls help me!!

Thanks in advance, Varsha.

7 Answers

Below is the utility method I have written to get value of any node from the root Document object and a given XPATH.

public String getValue(Document doc, String xPath) throws Exception {
   XPathFactory factory = XPathFactory.newInstance();
   XPath path = factory.newXPath();
   XPathExpression expression = path.compile(xPath);
   Node node = (Node) expression.evaluate(doc,XPathConstants.NODE);
   return node.getFirstChild().getNodeValue();
}

All the libraries are from java.xml.xpath and org.w3c.dom.

Now all you need the root document element and correct Path. For your example if will /ep/source/@type

So, basically XPAth is to navigate till the element you are after and followed by /@attributeName you are interested in.

Please node /ep/source@type won't work. (I wasted 30 min troubleshooting this).

Related