将.XML转换为HashMap

时间:2013-04-07 05:38:28

标签: java xml hashmap

我有像这样的.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;
    }

1 个答案:

答案 0 :(得分:2)

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