如何使用Java从XML文件中提取数据?

时间:2022-07-05 06:13:41

My XML file:

我的XML文件:

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

在Java中,如果输入为“Firefox”,则输出为mobile=false, minversion=2。

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

如何使用Java从XML获取数据?

5 个解决方案

#1


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.

您可以使用JAXB。首先,您需要从xml的创建者那里获得XSD(甚至DTD)。然后,您可以使用Java中的xjc之类的工具来创建类(和/或源代码),以便将XML字符串/文件解压缩到Java对象中。

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

这样做之后,就可以使用Java JAXB类从XML构建Java对象。一个简单的例子:

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

Check out this for more information.

更多信息请点击这里。

#2


1  

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

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

Check out the examples.

查看示例。

#3


1  

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

一个简单的方法是使用dom4j,我认为它比SAX更简单:http://dom4j.sourceforge.net/,但是需要更多的内存。

#4


1  

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

通常,它总是与解析XML相关联。试试这个:http://www.ibm.com/developerworks/library/x-javaxpathapi.html

Using XPathFactory you could do:

使用XPathFactory你可以做到:

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

#5


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.

您需要使用XML解析器。我建议XOM。它使解析XML文件变得轻而易举。他们也有很好的文档说明如何实现这一点。

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

#1


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.

您可以使用JAXB。首先,您需要从xml的创建者那里获得XSD(甚至DTD)。然后,您可以使用Java中的xjc之类的工具来创建类(和/或源代码),以便将XML字符串/文件解压缩到Java对象中。

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

这样做之后,就可以使用Java JAXB类从XML构建Java对象。一个简单的例子:

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

Check out this for more information.

更多信息请点击这里。

#2


1  

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

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

Check out the examples.

查看示例。

#3


1  

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

一个简单的方法是使用dom4j,我认为它比SAX更简单:http://dom4j.sourceforge.net/,但是需要更多的内存。

#4


1  

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

通常,它总是与解析XML相关联。试试这个:http://www.ibm.com/developerworks/library/x-javaxpathapi.html

Using XPathFactory you could do:

使用XPathFactory你可以做到:

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

#5


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.

您需要使用XML解析器。我建议XOM。它使解析XML文件变得轻而易举。他们也有很好的文档说明如何实现这一点。

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