Get value of XML tag using java

1.1k views Asked by At

I'm trying to read the value of "release" tag of a remote XML file and return it's value .I'm able to find the value of "release" tag using getElementText() but not by getElementValue()

Java Code..

 try {
URL url1 = new URL("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/gdd/GDDResources/maven-metadata.xml");
XMLStreamReader reader1 = XMLInputFactory.newInstance().createXMLStreamReader(url1.openStream());
String Latest = null;
while (reader1.hasNext()) {
    if (reader1.next() == XMLStreamConstants.START_ELEMENT) {
        if (reader1.getLocalName().equals("release")) {
            Latest = reader1.getElementText();
            break;
        }
    }
}
System.out.println("Latest version in Artifactory is :"+Latest);
} catch (IOException ex) {
 // handle exception
Logger.getLogger(SVNRepoConnector1.class.getName()).log(Level.SEVERE, null, ex);
} catch (XMLStreamException ex) {
// handle exception
Logger.getLogger(SVNRepoConnector1.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// close the stream

        }  

In the above code the value is being stored in a String variable but i want to store it in an integer variable so that i can perform operations like addition,subtraction on it afterwards..Please Help

1

There are 1 answers

0
Daniel Kec On

DOM Solution:

URL url1 = new URL("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/gdd/GDDResources/maven-metadata.xml");
InputSource xmlInputSource = new InputSource(url1.openStream());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document dom = dBuilder.parse(xmlInputSource);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//release");//all release elements
NodeList nodes = (NodeList) expr.evaluate(e,XPathConstants.NODESET);
ArrayList<Integer> releaseList = new ArrayList<Integer>();
for (int i = 0; i < nodes.getLength(); i++) {
   Element releaseElem = (Element) nodes.item(i);
    releaseList.add(Integer.parseInt(releaseElem.getText()));
}

Just catch the exceptions.