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

时间:2023-02-05 17:04:50

I have the a string in XML format. I want to read it and get the values of the elements.

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

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.

我想得到年龄和名字的价值。

6 个解决方案

#1


28  

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

#2


6  

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())

#3


4  

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

#4


2  

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

#5


0  

Just as a tidbit for users with more COMPLICATED XMLs, as I do. If you have elements with the same name but, different attributes, for example:

对于拥有更多COMPLICATED XML的用户来说,就像我一样。如果您具有相同名称但具有不同属性的元素,例如:

<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.

提取它们的方法是遵循@vault的答案,但是,确保更改.item(int)函数中的值。

If you want the first field you use .item(0). If you want the second you use .item(1)

如果你想要第一个字段,你可以使用.item(0)。如果你想要第二个你使用.item(1)

Hope this helps for future users as it did for me.

希望这对未来的用户有所帮助。

#6


0  

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

#1


28  

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

#2


6  

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())

#3


4  

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

#4


2  

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

#5


0  

Just as a tidbit for users with more COMPLICATED XMLs, as I do. If you have elements with the same name but, different attributes, for example:

对于拥有更多COMPLICATED XML的用户来说,就像我一样。如果您具有相同名称但具有不同属性的元素,例如:

<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.

提取它们的方法是遵循@vault的答案,但是,确保更改.item(int)函数中的值。

If you want the first field you use .item(0). If you want the second you use .item(1)

如果你想要第一个字段,你可以使用.item(0)。如果你想要第二个你使用.item(1)

Hope this helps for future users as it did for me.

希望这对未来的用户有所帮助。

#6


0  

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