2

My XML file:

<?xml version="1.0" encoding="UTF-8"?>
<devices>
 <device mobile="true" supported="false">Windows CE</device>
 <device mobile="false" minVersion="2">Firefox</device>
 <device mobile="false" minVersion="3">Safari</device>
 <device mobile="false" minVersion="6">MSIE</device>
 <device mobile="false" minVersion="1">Chrome</device>
</devices>

From Java, if we give input as "Firefox", the output should be mobile=false and minversion=2.

How can I get this data from the XML using Java?

1
  • 1
    Did you try to search before? This has been asked tons of times before. In this specific case (where you want to extract a few values from some bigger XML), I'd suggest you google for "XPath Java". Commented Apr 27, 2011 at 14:45

5 Answers 5

2

You can use JAXB. First you need to get the XSD (or even DTD) from the creator of the xml. Then you can use a tool like xjc from Java to create your classes (and/or source code) for unpacking the XML string/file into Java objects.

Once you've done that, you can use the Java JAXB classes to build Java objects from the XML. For a simple example:

(MyObject)JAXBContext.newInstance("package.where.xjc.generated.the.classes")
    .createUnmarshaller()
    .unmarshal(readerOrStreamOrFileOrURL);

Check out this for more information.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, You can also start with Java classes and then map them to the desired XML using JAXB annotations.
1

http://java.sun.com/developer/codesamples/xml.html#dom

Check out the examples.

Comments

1

An easy way is using dom4j, that I think it is simpler than SAX: http://dom4j.sourceforge.net/ , but needs more memory.

Comments

1

Generally, it's always connected with parsing XML. Try this: http://www.ibm.com/developerworks/library/x-javaxpathapi.html

Using XPathFactory you could do:

import java.util.*;
import java.lang.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.xpath.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("Devices.xml");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//devices/device[@mobile='false' and @minVersion='2']/text()");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result; 
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue());
    } 


    }
}

The output:

Firefox

2 Comments

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true);DocumentBuilder builder = domFactory.newDocumentBuilder();Document doc = builder.parse("Device.xml");XPathFactory factory = XPathFactory.newInstance();XPath xpath = factory.newXPath();XPathExpression expr = xpath.compile("//devices/device[@mobile='true' and @minVersion='2']/text()");Object result = expr.evaluate(doc, XPathConstants.NODESET);NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) {System.out.println(nodes.item(i).getNodeValue());}
@gowtham: sorry, there was error in logic ('true' instead of 'false' for mobile). I've edited my post - it works now (tested).
0

You'll need to use an XML parser. I recommend XOM. It makes parsing XML files a breeze. They have good documentation on how to accomplish this as well.

An example:

Document doc = new XmlBuilder().build(new File("path/to/file"));
Element devicesElement = doc.getRootElement();
Elements deviceElements = devicesElement.getChildElements();

for (int i = 0; i < deviceElements.size(); i++) {
    Element curDevice = deviceElements.get(i);
    ....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.