-2

我想code = "ABC" 使用 xPath 检查我的 xml 文件中是否存在。你能建议我一些方法吗?

<metadata>
 <codes class = "class1">
      <code code = "ABC">
            <detail "blah blah"/>
        </code>
  </codes>
  <codes class = "class2">
      <code code = "123">
            <detail "blah blah"/>
        </code>
  </codes>
 </metadata>

[编辑] 我做了以下。它返回空值。

            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression expr = xPath.compile("//codes/code[@ code ='ABC']");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println("nodes: "+ nodes.item(i).getNodeValue()); 
            }
4

1 回答 1

4

我不知道你是如何测试你的代码的,因为<detail "blah blah"/>它是一个不正确的 xml 构造,它应该是<detail x="blah blah"/>一个名称-值对!

对于 XPath 表达式"//codes/code[@ code ='ABC']"nodes.item(i).getNodeValue())将是null因为它将返回一个元素。请参阅下面的 Javadoc 注释:

在此处输入图像描述

A working sample:

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Test 
{
    public static void main(String[] args) throws Exception
    {
        Document doc = getDoc();
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile("//codes/code[@code ='ABC']");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        System.out.println("Have I found anything? " + (nodes.getLength() > 0 ? "Yes": "No"));

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

    }

    private static Document getDoc() 
    {
        String xml = "<metadata>"+
                 "<codes class = 'class1'>"+
                      "<code code='ABC'>"+
                            "<detail x='blah blah'/>"+
                        "</code>"+
                  "</codes>"+
                  "<codes class = 'class2'>"+
                      "<code code = '123'>"+
                            "<detail x='blah blah'/>"+
                        "</code>"+
                  "</codes>"+
                 "</metadata>";


        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            DocumentBuilder db = dbf.newDocumentBuilder();
            Document dom = db.parse(new ByteArrayInputStream(xml.getBytes()));
            return dom;

        }catch(Exception pce) {
            pce.printStackTrace();
        }
        return null;
    }
}
于 2012-07-25T14:26:01.020 回答