【问题标题】:Get value of XML tag using java使用java获取XML标签的值
【发布时间】:2014-11-24 11:40:48
【问题描述】:

我正在尝试读取远程 XML 文件的“发布”标签的值并返回它的值。我可以使用 getElementText() 找到“发布”标签的值,但不能通过 getElementValue()

Java 代码..

 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

        }  

在上面的代码中,值被存储在一个字符串变量中,但我想把它存储在一个整数变量中,这样我就可以在之后对其执行加法、减法等操作..请帮助

【问题讨论】:

  • 我建议您将“在 XML 中查找值”与“增加值”部分隔离开来……这样您一次只能处理一件事。如果增量部分给您带来麻烦,您不需要任何 XML 代码来处理它...您只需使用String incrementValue(String existingValue) 之类的方法。然后,您也可以非常轻松地编写一堆单元测试......
  • 变量和方法名应该小写
  • 帮自己一个忙,使用 DOM 解析器。
  • 如果我使用 DOM 解析器,我是否能够在之后对最新的字符串执行加法、减法等操作??

标签: java xml xmlreader xmlstreamreader


【解决方案1】:

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

只捕获异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    相关资源
    最近更新 更多