如何在Java中从XML字符串中获取所有元素的值?

17

我有一个XML格式的字符串,希望能够读取其中的元素值。

我尝试使用Java的JAXBContext unmarshell,但这需要创建一个对我来说不必要的类。

字符串:

<customer>
    <age>35</age>
    <name>aaa</name>
</customer>

我想获取年龄姓名的值。


6个回答

54

这是您的 XML:

String xml = "<customer><age>35</age><name>aaa</name></customer>";

这是解析器:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(xml));

Document doc = builder.parse(src);
String age = doc.getElementsByTagName("age").item(0).getTextContent();
String name = doc.getElementsByTagName("name").item(0).getTextContent();

很抱歉,如何修复builder.parse(src)的错误:com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse()没有可适用于参数类型为(jdk.internal.org.xml.sax.InputSource)值为[jdk.internal.org.xml.sax.InputSource@4398571a]的方法\n可能的解决方案是:parse(java.io.File), parse(java.io.InputStream), parse(java.lang.String), parse(org.xml.sax.InputSource), parse(org.xml.sax.InputSource), parse(java.io.InputStream, java.lang.String) - Pham X. Bach
1
你可能导入了jdk.internal.org.xml.sax.InputSource而不是org.xml.sax.InputSource - vault
谢谢,我是Java的新手,很难搜索应该导入哪个库来使用一个类。 - Pham X. Bach

11

JSoup对XML有很好的支持

import org.jsoup.*     
import org.jsoup.nodes.*   
import  org.jsoup.parser.*

//str is the xml string 
String str = "<customer><age>35</age><name>aaa</name></customer>"
Document doc = Jsoup.parse(str, "", Parser.xmlParser());
System.out.println(doc.select("age").text())

7

在标准API中使用XPath

String xml = "<customer>" + "<age>35</age>" + "<name>aaa</name>"
    + "</customer>";
InputSource source = new InputSource(new StringReader(xml));
XPath xpath = XPathFactory.newInstance()
                          .newXPath();
Object customer = xpath.evaluate("/customer", source, XPathConstants.NODE);
String age = xpath.evaluate("age", customer);
String name = xpath.evaluate("name", customer);
System.out.println(age + " " + name);

2

JDOM 很容易使用:

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("c:\\file.xml");
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
List list = rootNode.getChildren("customer");

for (int i = 0; i < list.size(); i++) {

    Element node = (Element) list.get(i);

    System.out.println("Age : " + node.getChildText("age"));
    System.out.println("Name : " + node.getChildText("name"));         
}

1

对于那些像我一样有更复杂XML的用户,这是一个小提示。如果你有相同名称但不同属性的元素,例如:

<field tag="8"> Country </field>
<field tag="12"> State </field>

提取它们的方法是按照 @vault 的 答案,但请确保更改 .item(int) 函数中的值。
如果您想要第一个字段,使用 .item(0)。如果您想要第二个字段,则使用 .item(1)
希望这对未来的用户有所帮助,就像对我一样。

0
我使用这个通用方法迭代所有元素:
public static void getElementValues(Node node) {
    NodeList nodeList = node.getChildNodes();
    for (int i = 0, len = nodeList.getLength(); i < len; i++) {
        Node currentNode = nodeList.item(i);
        if (len == 1 && currentNode.getNodeType() == Node.TEXT_NODE) {
            System.out.println(node.getLocalName() + "=" + currentNode.getTextContent());
        }
        else if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            getElementValues(currentNode);
        }
    }
}

结果:

age = 35
name = aaa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接