使用NodeList解析Xml

时间:2014-11-07 16:33:08

标签: java xml dom xml-parsing

我遇到了使用Java dom进行XML解析的问题。

我有以下XML

    <XXX>AA</XXX>
    <YYY>BB</YYY>
    <Params>
    <Param>
        <ParamID>10</ParamID>
        <value>
            <val1>1</val1>
            <val2>2</val2>
            <val3>3</val3>
        </value>
    </Param>
    <Param>
        <ParamID>20</ParamID>
        <value>
            <val1>4</val1>
            <val2>5</val2>
            <val3>6</val3>
        </value>
    </Param>
</Params>

我有这个java代码

   String targetNodeName = "Params";

NodeList nodes = getParents(xmlString, targetNodeName);
for (int i = 0 ; i < nodes.getLength() ; i++){
    Element currentElement = nodes.item(i);
    NodeList fields = currentElement.getChildNodes();               
    for (int j = 0 ; j < fields.getLength() ; j++){
        Node currentFieldElement = fields.item(j);
        if (currentFieldElement != null && currentFieldElement.getNodeType() == Node.ELEMENT_NODE) {
            String key =  currentFieldElement.getNodeName();
            String value = currentFieldElement.getTextContent();
            Hashtable.put(key, value);
        }
    }


private static NodeList getParents (String xmlString, String tagName) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse( new InputSource( new StringReader( xmlString ) ) );
    return document.getElementsByTagName(tagName);
}

问题是我希望将结果作为映射(例如hashmap)与对

示例:

{ <XXX, [AA] > , <YYY, [BB] > , <10, [1 , 2 , 3] > ....}

我该怎样做?

谢谢

1 个答案:

答案 0 :(得分:2)

    NodeList nodes = getParents(getTestingResponse(), targetNodeName);
    HashMap<Integer, Object> hm = new HashMap<Integer, Object>();
    for (int i = 0 ; i < nodes.getLength() ; i++){
        Element currentElement = (Element) nodes.item(i);
        NodeList fields = currentElement.getChildNodes();               
        for (int j = 0 ; j < fields.getLength() ; j++){
            Node currentFieldElement = fields.item(j);
            List<Integer> integer = new ArrayList<Integer>();
            List<Integer> integerNew = new ArrayList<Integer>();
            if (currentFieldElement != null && currentFieldElement.getNodeType() == Node.ELEMENT_NODE) {
                String key =  currentFieldElement.getNodeName();
                String[] value = currentFieldElement.getTextContent().split("\n");

                for (String v : value) {
                    System.out.println(v);
                    try {
                        integer.add(Integer.parseInt(v.trim()));
                    } catch(Exception e) {}                     
                }

                integerNew.add(integer.get(1));
                integerNew.add(integer.get(2));
                integerNew.add(integer.get(3));
                hm.put(integer.get(0), integerNew);
            }
        }
    }
    System.out.println(hm);

或者,您可以尝试以下代码:

      try 
      { 
        // File inputFile = new File("Input.xml");

         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

         Document doc = dBuilder.parse(DomParserPuCm.class.getResourceAsStream("Input.xml"));

         doc.getDocumentElement().normalize();

         System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

         NodeList params = doc.getElementsByTagName("Params");
         HashMap<Integer, Object> paramsHM = new HashMap<Integer, Object>();
         System.out.println(params.getLength());

         for (int p = 0; p < params.getLength(); p++) {
             NodeList param = params.item(p).getChildNodes();

             if (param.item(p).getLocalName() != null) {

                 for (int z = 0; z < param.getLength(); z++) {
                     System.out.println(param.item(z).getLocalName());
                     if(param.item(z).getLocalName().equals("Param")) {
                         NodeList children = param.item(z).getChildNodes();
                         for (int c = 0; c < children.getLength(); c++) {
                             int paramID = 0;
                             int value1 = 0;
                             int value2 = 0;
                             int value3 = 0;
                             List<Integer> valueList = new ArrayList<Integer>(); 

                             if (children.item(c).getLocalName() != null) {
                                 if (children.item(c).getLocalName().equals("ParamID")) {
                                     try{paramID = Integer.parseInt(children.item(c).getFirstChild().getNodeValue());}catch(Exception e){}
                                 } else if (children.item(c).getLocalName().equals("value")) {
                                     NodeList values = children.item(c).getChildNodes();                                         
                                     try{value1 = Integer.parseInt(values.item(0).getFirstChild().getNodeValue());}catch(Exception e){}
                                     try{value2 = Integer.parseInt(values.item(1).getFirstChild().getNodeValue());}catch(Exception e){}
                                     try{value3 = Integer.parseInt(values.item(2).getFirstChild().getNodeValue());}catch(Exception e){}
                                     valueList.add(value1);
                                     valueList.add(value2);
                                     valueList.add(value3);
                                 }
                             }

                             System.out.print(valueList);
                             paramsHM.put(paramID, valueList);
                         }
                     }
                 }

             }
         }

         System.out.print(paramsHM);

      } 
      catch (Exception e) 
      {
         e.printStackTrace();
      }