简体   繁体   中英

Read Tag value of Remote XML file using Java

I'm trying to read a XML file stored in a remote location and print that value of the tag "latest". Currently I'm able to print the contents of entire XML file but i want to print only the value of "latest" tag which is 3.6.8 .I can't understand which in build packages to use for readiing the XML file..Please help

The XML file

    <?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>

The Java code..

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

   }
   }

EDIT 1:

I used the answer provided by @Khalid Alqinyah to solve my issue.The final java code.

   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


     }   

 }

 }

You don't need external libs. Use 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;
}

To invoke the method above, use:

String latestVersion = readLatestVersion("http://example.org/maven-metadata.xml");

To get things right, ensure you have the following imports:

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;

One possible way is to read the stream line by line and stop when you find what you're looking for.

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
}

I do things like that with 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());
    }
}

If you look at the project site, there is even a tutorial reading maven pom.xml files.

If you are limited to use standard java features, i would suggest you further reading about the SAXParser class of standard JDK. It is a convenient method to parse XML documents in Java.

One option is to use XPath. Try this:

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

If available within your project, you could use org.apache.maven.artifact.repository.metadata to do the parsing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM