错误:java.lang.String无法强制转换为org.w3c.dom.Node

时间:2012-03-15 01:41:09

标签: java xml xpath

我正在尝试解析xml字符串,但我收到java.lang.String cannot be cast to org.w3c.dom.Node错误。

这是我正在使用的代码:

        XPathFactory xPathFactory = XPathFactory.newInstance();

        XPath xPath = xPathFactory.newXPath();

        String expression = "//Home/ListOfCustomers";

        XPathExpression xPathExpression = xPath.compile(expression);

        Object nl = xPathExpression.evaluate(xmlResp);

这是XML字符串的构造方式:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Home>
      <ListOfCustomers type="Regular" count="939">
           <Customer>
            <CustName>xyz</CustName>
           </Customer>
           <Customer>
            <CustName>abc</CustName>
           </Customer>
           <Customer>
            <CustName>def</CustName>
           </Customer>
       </ListOfCustomers>
</Home>

我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

  

Object nl = xPathExpression.evaluate(xmlResp);

这是问题所在。对于evaluate方法的单个参数,它期望输入类型为InputSource或Object的变量,是否要将xmlResp声明为其中任何一个?另外,这两个方法都返回String类型,那么为什么要赋予Object类型的变量?

由于您有xml文件,为什么不将xmlResp初始化为InputSource类型?然后在输入源上使用xPathExpression评估?如下所示。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class XMLParser
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        try {

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();

        InputSource doc = new InputSource(new InputStreamReader(new FileInputStream(new File("file.xml"))));

        String expression = "//Home/ListOfCustomers";
        XPathExpression xPathExpression = xPath.compile(expression);

        NodeList elem1List = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
        xPathExpression = xPath.compile("@type");

        for (int i = 0; i < elem1List.getLength(); i++)
        {
            System.out.println(xPathExpression.evaluate(elem1List.item(i), XPathConstants.STRING)); 
        }


        }
        catch (XPathExpressionException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:1)

快速查看文档: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/xpath/XPathExpression.html#evaluate(java.lang.Object

然后api为编译定义了这个: item - 起始上下文(例如,节点或节点列表)。

因此假设这是您正在使用的方法,看起来您需要发送节点 - 或节点列表,而不仅仅是字符串。