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

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


Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

<?xml version="1.0" encoding="UTF-8"?><ep>    <source type="xml">TEST</source>    <source type="text"></source></ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document doc = builder.parse("uri to xmlfile");XPathFactory xPathfactory = XPathFactory.newInstance();XPath xpath = xPathfactory.newXPath();XPathExpression expr = xpath.compile("//ep/source[@type]");NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);for (int i = 0; i < nl.getLength(); i++){    Node currentItem = nl.item(i);    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();    System.out.println(key);}


try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();    Document dDoc = builder.parse("d://utf8test.xml");    XPath xPath = XPathFactory.newInstance().newXPath();    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);    for (int i = 0; i < nodes.getLength(); i++) {        Node node = nodes.item(i);        System.out.println(node.getTextContent());    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.


I'm happy that this snippet works fine:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();Document document = db.parse(new File("config.xml"));NodeList nodeList = document.getElementsByTagName("source");for(int x=0,size= nodeList.getLength(); x<size; x++) {    System.out.println(nodeList.item(x).getAttributes().getNamedItem("type").getNodeValue());}