我有一个XML格式的字符串,希望能够读取其中的元素值。
我尝试使用Java的JAXBContext unmarshell,但这需要创建一个对我来说不必要的类。
字符串:
<customer>
<age>35</age>
<name>aaa</name>
</customer>
我想获取年龄和姓名的值。
我有一个XML格式的字符串,希望能够读取其中的元素值。
我尝试使用Java的JAXBContext unmarshell,但这需要创建一个对我来说不必要的类。
字符串:
<customer>
<age>35</age>
<name>aaa</name>
</customer>
我想获取年龄和姓名的值。
这是您的 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();
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. Bachjdk.internal.org.xml.sax.InputSource
而不是org.xml.sax.InputSource
。 - vaultJSoup对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())
在标准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);
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"));
}
对于那些像我一样有更复杂XML的用户,这是一个小提示。如果你有相同名称但不同属性的元素,例如:
<field tag="8"> Country </field>
<field tag="12"> State </field>
.item(int)
函数中的值。.item(0)
。如果您想要第二个字段,则使用 .item(1)
。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