-1

我有这样的 .xml 文件。我想将此文件转换为 HashMap 并在 Java 中反转。您能告诉我如何将其转换为 HashMap 文件吗?谢谢 ...

这是 .xml 文件:

<RelationShipTypes>
        <RelationShipType key="1" name="Organization Unit"/>
        <RelationShipType key="2" name="Employee"/>
        <RelationShipType key="3" name="Customer"/>
        <RelationShipType key="4" name="Supplier"/>
        <RelationShipType key="5" name="Agency"/>
        <RelationShipType key="6" name="Partner"/>
        <RelationShipType key="7" name="SALES AGENT"/>
        <RelationShipType key="8" name="End User"/>
        <RelationShipType key="9" name="Other"/>
    </RelationShipTypes>

这是代码:

  public static Map<String, String> convertNodesFromXml(String xml) throws SAXException, IOException, ParserConfigurationException {
        try {
            InputStream is = new ByteArrayInputStream(xml.getBytes());
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);

            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(is);
            return createMap(document.getDocumentElement());
        } catch (SAXException ex) {
            Logger.getLogger(BaseDataLoader.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        } catch (IOException ex) {
            Logger.getLogger(BaseDataLoader.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(BaseDataLoader.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }
    }

    public static Map<String, String> createMap(Node node) {
        Map<String, String> map = new HashMap<String, String>();
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.hasAttributes()) {
                for (int j = 0; j < currentNode.getAttributes().getLength(); j++) {
                    Node item = currentNode.getAttributes().item(i);
                    map.put(item.getNodeName(), item.getTextContent());
                }
            }
            if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
                map.putAll(createMap(currentNode));
            } else if (node.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                map.put(node.getLocalName(), node.getTextContent());
            }
        }
        return map;
    }
4

1 回答 1

2

您需要先解析 XML。尝试使用DOM 解析器。谷歌它你会得到示例代码。然后您可以填充HashMap中的值。这是示例代码。

于 2013-04-07T05:45:48.060 回答