2013-03-06 120 views
2

現在我想解析來自webservice的xml。爲了解析,我使用了xpath和java。我有以下代碼:使用xpath和java解析xml

package test.client; 

import com.sun.org.apache.xpath.internal.NodeSet; 
import java.io.FileReader; 
import java.io.StringReader; 
import javax.lang.model.element.Element; 
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathConstants; 
import javax.xml.xpath.XPathFactory; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 

public class GetAlarmsCriticalDataCenterLinksDown { 
    public static void main(String args[]) throws Exception { 
     try { 
      GetAlarms ga = new GetAlarms(); 
      String xml = ga.getAlarms(
       "Alarms", 
       "C:/Documents and Settings/Administrator/My Documents/NetBeansProjects/WebSpectrumDemo/src/java/com/xml/Alarms/GetAlarmsCriticalDataCenterLinksDown.xml"); 
      System.out.println("Response XML:\n " + xml); 
      XPathFactory factory = XPathFactory.newInstance(); 
      XPath xPath = factory.newXPath(); 
      String loc = ""; 
      NodeList nodes = (NodeList) xPath.evaluate(
       "//alarm-response-list/alarm-responses/alarm", 
       new InputSource(new StringReader(xml)), 
       XPathConstants.NODESET); 
      System.out.println("Success : " + nodes.getLength()); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 
} 

和我的字符串XML是什麼樣子

<?xml version="1.0" encoding="UTF-8"?> 
<alarm-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" 
        error="EndOfResults" throttle="2" total-alarms="2"> 
    <alarm-responses> 
    <alarm id="51230f5c-11fe-1002-01bc-000c296b3541"> 
     <attribute id="0x1006e">HBBCPMPLSR1.hdfcami.com</attribute> 
     <attribute id="0x11f84" error="NoSuchAttribute" /> 
     <attribute id="0x118cd" /> 
     <attribute id="0x11f4e">1361252188</attribute> 
    </alarm> 
    <alarm id="512313db-c5ee-1003-01bc-000c296b3541"> 
     <attribute id="0x1006e">HBBCPINTR0.hdfcami.com</attribute> 
     <attribute id="0x11f84" error="NoSuchAttribute" /> 
     <attribute id="0x118cd" /> 
     <attribute id="0x11f4e">1361253339</attribute> 
    </alarm> 
    </alarm-responses> 
</alarm-response-list> 

但我卡住了。我得到nodes.getLength() = 0

任何幫助將不勝感激。 我想解析整個XML並獲取屬性的值。

+0

如果從'alarm-response-list'中刪除命名空間,會發生什麼? – zwets 2013-03-06 05:54:44

回答

4

您需要在您的XPath對象上設置命名空間。使用XPath.setNamespaceContext()來做到這一點。或者,您可以在XPath表達式中使用本地名稱,例如//*[local-name()='alarm-response-list']/*[local-name()='alarm-responses']/*[local-name()='alarm']但名稱空間選項更好。

有關在XPath表達式中使用名稱空間的大量信息已在另一個答案here中。

+0

得到響應的長度後,我想獲得每個屬性的值,但我不會得到該屬性的值。我使用代碼如 – 2013-03-06 07:27:23

+0

感謝您的快速回復............ .. – 2013-03-06 07:32:39

+0

要獲取屬性元素,遍歷NodeList中的所有節點,然後將出來的節點投射到Element元素中。從這些元素中可以獲得子元素,XML屬性,文本內容等。 – prunge 2013-03-06 08:14:15