使用Java读取远程XML文件的标记值

时间:2014-10-30 13:25:09

标签: java xml xml-parsing

我试图读取存储在远程位置的XML文件并打印标签" latest"的值。目前我能够打印整个XML文件的内容,但我只想打印"最新"的值。标签是3.6.8。我无法理解构建包中用于读取XML文件的内容..请帮助

XML文件

    <?xml version="1.0" encoding="UTF-8"?>
    <metadata>
    <groupId>com.avocent.commonplatform.cps.symbols</groupId>
    <artifactId>MasterData</artifactId>
    <versioning>
    <latest>3.6.8</latest>
    <release>3.6.8</release>
    <versions>
    <version>1.0.19</version>
    <version>1.0.27</version>
    <version>1.0.29</version>
    <version>1.0.30</version>
    <version>1.0.32</version>
    <version>1.0.33</version>
    <version>1.0.35</version>
    <version>2.0.1</version>
    <version>2.0.3</version>
    <version>2.0.4</version>
    <version>2.0.5</version>
    <version>2.0.6</version>
    <version>2.0.7</version>
    <version>3.0.1</version>
    <version>3.0.2</version>
    <version>3.0.3</version>
    <version>3.0.4</version>
    <version>3.0.5</version>
    <version>3.0.6</version>
    <version>3.0.7</version>
    <version>3.0.9</version>
    <version>3.0.10</version>
    <version>3.0.11</version>
    <version>3.0.13</version>
    <version>3.4.0</version>
    <version>3.5.0</version>
    <version>3.5.1</version>
    <version>3.5.2</version>
    <version>3.5.3</version>
    <version>3.5.4444</version>
    <version>3.6.0</version>
    <version>3.6.1</version>
    <version>3.6.5</version>
    <version>3.6.6</version>
    <version>3.6.7</version>
    <version>3.6.8</version>
    </versions>
    <lastUpdated>20141016143914</lastUpdated>
    </versioning>
    </metadata>

Java代码..

    public class MavenMetadataReader {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    BufferedReader reader = null;
    try {
        URL url = new URL("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/MasterData/maven-metadata.xml");

        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        while (reader.ready()) {
            System.out.println(reader.readLine());
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(MavenMetadataReader.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MavenMetadataReader.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(MavenMetadataReader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

   }
   }

编辑1:

我使用了@Khalid Alqinyah提供的答案来解决我的问题。最终的java代码。

   public class MavenMetadataReader {


/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws XMLStreamException {

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


     }   

 }

 }

6 个答案:

答案 0 :(得分:1)

您不需要外部库。使用XPath

public String readLatestVersion(String xmlUri) throws Exception {

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(xmlUri);

    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/metadata/versioning/latest";
    String latestVersion = xPath.compile(expression).evaluate(document);

    return latestVersion;
}

要调用上述方法,请使用:

String latestVersion = readLatestVersion("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/MasterData/maven-metadata.xml");

更新

上面的代码需要以下导入:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

答案 1 :(得分:1)

一种可能的方法是逐行读取流,并在找到所需内容时停止。

XMLStreamReader reader = null;
try {
    URL url = new URL("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/MasterData/maven-metadata.xml");
    reader = XMLInputFactory.newInstance().createXMLStreamReader(url.openStream());
    String latest;
    while (reader.hasNext()) {
        if (reader.next() == XMLStreamConstants.START_ELEMENT) {
            if (reader.getLocalName().equals("latest")) {
                latest = reader.getElementText();
                break;
            }
        }
    }
} catch (IOException ex) {
    // handle exception
} catch (XMLStreamException ex) {
    // handle exception
} finally {
    // close the stream
}

答案 2 :(得分:0)

我用XMLBeam做了类似的事情:

class Answer {
    @XBDocUrl("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/MasterData/maven-metadata.xml")
    public interface MavenMetadata {
        @XBRead("//latest")
        String getLatest();
    }
    public static void main(String[] args) {
        MavenMetadata metadata = new XBProjector().io().fromURLAnnotation(MavenMetadata.class);
        System.out.println(metadata.getLatest());
    }
}

如果查看项目站点,甚至有一个教程读取maven pom.xml文件。

答案 3 :(得分:0)

如果您只能使用标准的java功能,我建议您进一步阅读SAXParser标准JDK类。这是一种用Java解析XML文档的便捷方法。

答案 4 :(得分:0)

一种选择是使用XPath。试试这个:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("http://hsv-artifactory.emrsn.org:8081/artifactory/libs-release-local/com/avocent/commonplatform/cps/symbols/MasterData/maven-metadata.xml");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//latest").evaluate(doc);

答案 5 :(得分:0)

如果在项目中可用,则可以使用org.apache.maven.artifact.repository.metadata进行解析。

import java.io.InputStream;
import java.net.URL;    
import org.apache.maven.artifact.repository.metadata.Metadata;
import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader;

[...]

URL url = new URL("http://repo1.maven.org/maven2/org/apache/maven/maven-repository-metadata/maven-metadata.xml");       
InputStream inputStream = url.openStream();
MetadataXpp3Reader metadataXpp3Reader = new MetadataXpp3Reader();
Metadata metadata = metadataXpp3Reader.read(inputStream);
inputStream.close();

System.out.println("groupId: " + metadata.getGroupId());
System.out.println("artifactId: " + metadata.getArtifactId());
System.out.println("latest: " + metadata.getVersioning().getLatest());