2

这是我要加载 xml "test" 的程序的代码。当我构建这个时,我被加载并且“0”中没有节点。加载或x路径有问题。我正在使用日食。请帮我解决这个问题。

<?xml version="1.0"?>
<resourses>
    <resourse status="1">
        <name>resourse1</name>
        <type>1</type>
    </resourse>

    <resourse  status="2">
        <name>resourse2</name>
        <type>2</type>
    </resourse>

          <resourse  status="3">
        <name>resourse3</name>
        <type>3</type>
    </resourse>

</resourses>





public class xml_l 
{
public static void main(String[] args)

throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException 

{
DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);

DocumentBuilder builder = domFactory.newDocumentBuilder();

Document doc = builder.parse("/home/user/test/test.xml");
if (doc==null)
{

System.out.println("not loaded");   

}
else
{

    System.out.println(" loaded "); 
}

XPath xpath = XPathFactory.newInstance().newXPath();


XPathExpression expr = xpath.compile("//resourse[status =1]/name/text()"); 

Object result = expr.evaluate(doc, XPathConstants.NODESET);

NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());

for (int i = 0; i < nodes.getLength(); i++)                                        // nodes.getLength()
{
System.out.println(nodes.item(i).getNodeValue());

}
}
}
4

1 回答 1

0

您需要在属性前面有一个“@”来通知 xPath 您正在寻找一个属性。

XPathExpression expr = xpath.compile("//resourse[@status=1]/name/text()");

不是

XPathExpression expr = xpath.compile("//resourse[status=1]/name/text()"); 
于 2012-11-09T06:38:28.433 回答