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

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.

This question is related to java xml xmlnode xml-attribute

The answer is


use

document.getElementsByTagName(" * ");

to get all XML elements from within an XML file, this does however return repeating attributes

example:

NodeList list = doc.getElementsByTagName("*");


System.out.println("XML Elements: ");

        for (int i=0; i<list.getLength(); i++) {

            Element element = (Element)list.item(i);
            System.out.println(element.getNodeName());
        }

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method


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

Below is the code to do it in VTD-XML

import com.ximpleware.*;

public class queryAttr{
     public static void main(String[] s) throws VTDException{
         VTDGen vg= new VTDGen();
         if (!vg.parseFile("input.xml", false))
            return false;
         VTDNav vn = vg.getNav();
         AutoPilot ap = new AutoPilot(vn);
         ap.selectXPath("//xml/ep/source/@type");
         int i=0;
         while((i = ap.evalXPath())!=-1){
               system.out.println(" attr val ===>"+ vn.toString(i+1));

         }
     }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to xmlnode

how to get the attribute value of an xml node using java How to modify existing XML file with XmlDocument and XmlNode in C# Modify XML existing content in C# What's the difference between an element and a node in XML?

Examples related to xml-attribute

how to get the attribute value of an xml node using java Android : difference between invisible and gone? XSLT - How to select XML Attribute by Attribute?