[英]How to get values of all elements from XML string in Java?
我有一个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();
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())
在标准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"));
}
正如我所做的那样,对于拥有更多COMPLICATED XML的用户来说,这也是一个小问题。 如果您具有相同名称但具有不同属性的元素,例如:
<field tag="8"> Country </field>
<field tag="12"> State </field>
提取它们的方法是遵循.item(int)
的答案,但是,确保更改.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.