3

现在我想解析来自 web 服务的 xml。对于解析,我使用了 xpath 和 java。我有以下代码:

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 并获取属性的值。

4

1 回答 1

4

XPath您需要在对象上设置命名空间。用于XPath.setNamespaceContext()执行此操作。或者,您可以只在 XPath 表达式中使用本地名称,例如,//*[local-name()='alarm-response-list']/*[local-name()='alarm-responses']/*[local-name()='alarm']但命名空间选项更好。

关于使用带有 XPath 表达式的名称空间的大量信息已经在此处的另一个答案中。

于 2013-03-06T06:01:18.717 回答