使用java获取XML标记的值

时间:2014-11-24 11:40:49

标签: java xml xmlreader xmlstreamreader

我正在尝试读取远程XML文件的“release”标记的值并返回它的值。我能够使用getElementText()找到“release”标记的值,但不能通过getElementValue()< / p>

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

        }  

在上面的代码中,值存储在一个String变量中,但我想将它存储在一个整数变量中,这样我就可以执行添加,减法等操作了......请帮助

1 个答案:

答案 0 :(得分:0)

DOM解决方案:

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

抓住例外。