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

Pat*_*tan 13 java xml xml-parsing

我有一个XML格式的字符串.我想阅读它并获取元素的值.

我已经尝试过Java JAXBContext unmarshell,但这需要创建类,这对我来说并不是必需的.

串:

<customer>
    <age>35</age>
    <name>aaa</name>
</customer>
Run Code Online (Sandbox Code Playgroud)

我想得到年龄名字的价值.

vau*_*ult 35

这是你的xml:

String xml = "<customer><age>35</age><name>aaa</name></customer>";
Run Code Online (Sandbox Code Playgroud)

这是解析器:

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();
Run Code Online (Sandbox Code Playgroud)


Gro*_*eek 7

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())
Run Code Online (Sandbox Code Playgroud)


McD*_*ell 5

在标准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);
Run Code Online (Sandbox Code Playgroud)