如何将xml字符串转换为map <string,string>

时间:2016-11-22 16:46:03

标签: java xml string hashmap

如何将XML的所有属性转换为Strings Map?我需要输出作为Map<String, String>中的键和值。即 <persons xmlns="http://www.sample.com/restapi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <delivery></delivery> <Order>1</Order> <person1> <personorder> <email>abc@abc.com</email> <name>Smith </name> <data> <approvedata> <approve> <Label>Consent</Label> <underline>false</underline> </approve> </approvedata> </data> </personorder> </person1> </persons> output : ............................... Order,1 email,abc@abc.com Label,Consent

{{1}}

1 个答案:

答案 0 :(得分:0)

我能够使用XPath来实现解决方案。 xpath查询搜索具有任何文本的叶元素。然后,一个简单的循环将xpath结果NodeList转换为Map。

以下是用一种方法包装的解决方案:

public static Map<String, String> getElementsWithText(Document xmlDoc) throws XPathException
{
    Map<String, String> elementsWithText = new HashMap<>();

    final String leafElementsWithTextXPathQuery = "//*[not(child::*) and text()]";
    XPath xPath =  XPathFactory.newInstance().newXPath();
    NodeList list = (NodeList)xPath.compile(leafElementsWithTextXPathQuery)
        .evaluate(xmlDoc, XPathConstants.NODESET);
    for (int i = 0; i < list.getLength() ; i++) {
        Node node = list.item(i);
        elementsWithText.put(node.getNodeName(), node.getTextContent());
    }
    return elementsWithText;
}

这是一个测试主程序,用于加载来自问题的xml:

public static void main(String[] args)
{
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document xmlDoc = builder.parse(new InputSource(new FileReader("C://Temp/xx.xml")));
        System.out.println(getElementsWithText(xmlDoc));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

println的输出:

{Order=1, underline=false, name=Smith , Label=Consent, email=abc@abc.com}
相关问题