您可以使用Java的XML解析库来将包含XML子节点的字符串转换为Map。下面是一个示例代码:

import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

public class XmlToMap {
    public static void main(String[] args) {
        String xmlString = '<root><name>John</name><age>25</age></root>';
        Map<String, String> xmlMap = parseXmlToMap(xmlString);
        System.out.println(xmlMap);
    }

    public static Map<String, String> parseXmlToMap(String xmlString) {
        Map<String, String> xmlMap = new HashMap<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlString)));
            NodeList nodeList = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    xmlMap.put(node.getNodeName(), node.getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlMap;
    }
}

在上述示例中,我们将包含XML子节点的字符串传递给parseXmlToMap方法并返回一个包含XML节点名称和文本内容的Map。输出结果为{name=John, age=25}。请注意,您需要将Java的XML解析库添加到您的项目中,例如javax.xml.parsers。

Java 将包含XML子节点的字符串转换为Map

原文地址: https://www.cveoy.top/t/topic/pczt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录