简体   繁体   English

如何从XML以字符串格式获取重复的标签值(Java)

[英]How to get repeated tag values from an xml in string format (Java)

I Have an xml in this format: 我有以下格式的xml:

<Container1>
<Description>one</Description>
</Container1>
<Container2>
<Description>Two</Description>
</Container2>

Am reading this xml to a String.(There is a reason why I cant parse the xml directly) Now from that String I need to take the values of all Description tags to a List Any clues on how to do this? 我正在将这个xml读取为一个字符串。(有一个原因我不能直接解析该xml)现在我需要从该字符串中将所有Description标签的值都放入一个列表中。有关如何执行此操作的任何线索?

Since you are receiving the xml ,you can parse it and the use XPath to extract the necessary information. 由于您正在接收xml,因此可以对其进行解析,并使用XPath提取必要的信息。 Please note that you need to pass the valid xml to builder#parse (I wrapped your xml in root element). 请注意,您需要将有效的xml传递给builder#parse (我将您的xml包装在root元素中)。

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class XPathExtractor {

    public static void main(String[] args) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
        String s = "<root>\n" +
                "<Container1>\n" +
                "<Description>one</Description>\n" +
                "</Container1>\n" +
                "<Container2>\n" +
                "<Description>Two</Description>\n" +
                "</Container2>\n" +
                "</root>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression descriptionExpr = xpath.compile("//Description/text()");
        Object result = descriptionExpr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }
    }
}

Outputs 产出

one
Two

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

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