java - Java如何从XML文档中获取键值对

标签 java xml xml-parsing

我有一个 XML 文档,我想从中检索该 XML 文档的键和值。然而我在两者上都遇到困难,我意识到我应该使用 Map 的数据类型,但我不确定如何实现这一点。

示例:

我有以下 XML 文件:

<?xml version="1.0"?>
    <config>
        <Request name="ValidateEmailRequest">
            <requestqueue>emailrequest</requestqueue>
            <responsequeue>emailresponse</responsequeue>
        </Request>
        <Request name="CleanEmail">
            <requestqueue>Cleanrequest</requestqueue>
            <responsequeue>Cleanresponse</responsequeue>
        </Request>
    </config>

我想编写一个方法来解析该文件并返回 XML 的节点 (key) 和值 (value) 的键值对。

如[requestqueue,emailrequest] [responsequeue,emailresponse]等...

我目前拥有的:

public Map<String, String> parseXML(File f) throws Exception {

    String xml = FileUtils.readFileToString(f);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = builder.parse(new InputSource(new StringReader(xml)));
    Element rootElement = document.getDocumentElement();

    // I'm stuck...

    return null;
}

任何帮助或协助将不胜感激,谢谢。

编辑:

我做了一些研究,发现一些东西可以打印我的值,但只有一个键“Return”

@Test
public void testConverter() throws Exception {
    String xml = ("xmlDir/request.xml");
    Map<String,String> map = convertNodesFromXml(xml);

    for(Map.Entry<String, String> entry: map.entrySet()) {
        String key = entry.getKey(); 
        String value = entry.getValue();

        logger.debug("Key: "+key+" Value: "+value);
    }

}



public static Map<String, String> convertNodesFromXml(String xml) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(xml);

    Element doc = document.getDocumentElement();
    logger.debug(doc.getFirstChild());

    return createMap(document.getDocumentElement());
}

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;
}

输出:

2015-08-18 15:01:31,651 : Key: Return Value: 



    136
    125
    SEPTEMBER
    250


    OCTOBER
    250
    125
    136


    136
    125
    250
    APRIL


    136
    JUNE
    250
    125


    MAY
    136
    250
    125


    136
    250
    125
    JANUARY


    136
    125
    250
    MARCH


    250
    AUGUST
    136
    125

  3000

    136
    125
    250
    DECEMBER


    136
    JULY
    125
    250


    136
    125
    FEBRUARY
    250

  1500
  555-11-2222

    125
    136
    NOVEMBER
    250

  1632


  1
  22000
  1
  22000




  1970-01-01


  555-11-2222


      CA

最佳答案

函数 getChildNodes() https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#getChildNodes()返回包含该节点的子节点的节点列表。也许您使用该函数来遍历您的节点树。 或者,您可以使用像 Jaxb 这样的框架,它将您的 xml 映射到 Java Pojos。有了这个 pojos,你就可以构建你的 map

关于java - Java如何从XML文档中获取键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32080330/

相关文章:

c# - 当 XML 再次包含相同的元素时,如何使用 C# 解析 XML?

xml - 用于语音识别语法规范 (SRGS) 的 XML 编辑器

java - fatal error :1:1: Content is not allowed in prolog. org.xml.sax.SAXParseException

java - 如何将代码提取到 Eclipse 中的静态方法中,并将字段作为参数传递?

xml - 编码 XML 时可选 "omitempty"?

java - 是否有等效于 java.util.Properties 的集合?

xml - 我应该使用哪个:preceding::or preceding-sibling::?

java - 在android中解析xml文件

java - 通过 CLI 构建 Repast 模型

java - GWT:Tomcat 无法序列化 'javax.net.ssl.SSLException'