Using Java to transform XML data into a Map structure is a common task in software development. This process allows you to easily access and manipulate XML data as key-value pairs. This guide will walk you through an example of converting XML to a Map using the DOM (Document Object Model) API in Java.

Converting XML to Map Using DOM

Here's a Java code example that demonstrates the process of converting XML to a Map:

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

public class XmlToMapExample {
    public static void main(String[] args) {
        String xml = '<request>
' + '<time_stamp>20190117115201</time_stamp>
' + '<input>
' + '<hos_code>T10001</hos_code>
' + '<dept_code1>NK</dept_code1>
' + '<dept_code2>HXNK</dept_code2>
' + '</input>
' + '</request>';

        Map<String, Object> map = xmlToMap(xml);
        System.out.println(map);
    }

    public static Map<String, Object> xmlToMap(String xml) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

            Element root = document.getDocumentElement();
            Map<String, Object> map = new HashMap<>();

            if (root.hasChildNodes()) {
                NodeList nodeList = root.getChildNodes();
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        Element element = (Element) node;
                        map.put(element.getNodeName(), element.getTextContent());
                    }
                }
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Explanation

  1. Import Necessary Classes: This code imports the required classes from the org.w3c.dom package for working with XML documents. These classes are essential for parsing and manipulating XML data.
  2. Create a Sample XML String: The code defines a sample XML string (xml) containing data that we want to convert to a Map.
  3. Parse XML into a DOM Object: The xmlToMap() function parses the XML string using the DOM API. It uses DocumentBuilderFactory and DocumentBuilder to create a DOM representation of the XML document.
  4. Iterate through Nodes: The code iterates through each child node of the root element (root). For each node, it checks if the node type is Node.ELEMENT_NODE. If it is, the node's name and text content are extracted.
  5. Populate the Map: The code stores the element's name as the key and its text content as the value in the map object.
  6. Return the Map: Finally, the xmlToMap() function returns the populated map containing the XML data.

Output

Running this code will produce the following output:

{hos_code=T10001, dept_code1=NK, time_stamp=20190117115201, dept_code2=HXNK}

Conclusion

This code effectively demonstrates how to convert XML data to a Map structure using Java's DOM API. The resulting Map provides a convenient way to access and manipulate the XML data as key-value pairs, making it easier to work with in your Java applications.

Java XML to Map: Efficiently Convert XML Data to Map Structures

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

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