简体   繁体   English

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

[英]How to get values of all elements from XML string in Java?

I have the a string in XML format. 我有一个XML格式的字符串。 I want to read it and get the values of the elements. 我想阅读它并获取元素的值。

I have tried Java JAXBContext unmarshell , but this needs creation of class which is not necessary for me. 我已经尝试过Java JAXBContext unmarshell ,但这需要创建类,这对我来说并不是必需的。

String: 串:

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

I want to get the values of age and name . 我想得到年龄名字的价值。

This is your xml: 这是你的xml:

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

And this is the parser: 这是解析器:

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 has a nice support for XML 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())

Using XPath in the standard API: 在标准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 is quite easy to use: 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"));         
}

Just as a tidbit for users with more COMPLICATED XMLs, as I do. 正如我所做的那样,对于拥有更多COMPLICATED XML的用户来说,这也是一个小问题。 If you have elements with the same name but, different attributes, for example: 如果您具有相同名称但具有不同属性的元素,例如:

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

The way to extract them is to follow @vault's answer but, make sure to change the value in the .item(int) function. 提取它们的方法是遵循.item(int)答案,但是,确保更改.item(int)函数中的值。

If you want the first field you use .item(0) . 如果你想要第一个字段,你可以使用.item(0) If you want the second you use .item(1) 如果你想要第二个你使用.item(1)

Hope this helps for future users as it did for me. 希望这对未来的用户有所帮助。

I iterate over all elements with this generic method: 我用这个泛型方法迭代所有元素:

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

Result: 结果:

age = 35
name = aaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM