需要帮助提取XML元素值并将它们存放到Java中的地图或其他类型的集合中

时间:2011-03-10 13:11:05

标签: java xml

下面的代码打印了我的XML文件的元素内容,但是,就我而言,我一直未能成功地提取元素值并将它们放在地图或其他类型的数组或列表中。任何帮助将不胜感激!!!!

  public class client
  {
     public static void main(String[] args )
     {
        int length = 0;
        String [] array;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {

           //Using factory get an instance of document builder
           DocumentBuilder builder  = factory.newDocumentBuilder();

           //create the document by parsing the actual file
           Document doc = builder.parse(new File ("server.xml"));

           //creat an XPath to be used in the extraction of the nodes
           XPathFactory xPFactory = XPathFactory.newInstance();
           XPath path = xPFactory.newXPath();

           //Extract ports
           XPathExpression portExpr
            = path.compile("//configuration/hostInfo/port");

           //Extract hosts
           XPathExpression hostExpr
            = path.compile("//configuration/hostInfo/host");

           Object pResult = portExpr.evaluate(doc, XPathConstants.NODESET);
           Object hResult = hostExpr.evaluate(doc, XPathConstants.NODESET);
           NodeList pNodes = (NodeList) pResult;
           NodeList hNodes = (NodeList) hResult;
           array = new String [(pNodes.getLength())*2];

           array = populateArray(array, pNodes, hNodes);
           for (int k = 0; k < array.length; k++)
               System.out.println( k+ "="+ array[k]);

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

  public static String[] populateArray (String array[], NodeList pNodes, NodeList hNodes){

        array[0]=pNodes.item(0).getTextContent();
        array[1]=hNodes.item(1).getTextContent();

        for (int i = 1; i < pNodes.getLength(); i++){
           array[2*i]= pNodes.item(i).getTextContent();
           array[(2*i)+1]= hNodes.item(i).getTextContent();
        }
        return array;
     }

  }

XML文件

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
   <hostInfo>
     <port>8189</port>
     <host>localhost</host>    
   </hostInfo>
   <hostInfo>
     <port>8190</port>
     <host>localhost</host>
   </hostInfo>
   <hostInfo>
     <port>8191</port>
     <host>localhost</host>
   </hostInfo>  
 </configuration>

1 个答案:

答案 0 :(得分:3)

您可以path.compile返回XPathExpression个对象。然后,您可以致电evaluate以获取NodeList的数组。

查看http://www.ibm.com/developerworks/library/x-javaxpathapi.htmlhttp://download.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/package-summary.html