-2

xPathを使用してxmlファイルに存在することを確認したいのですcode = "ABC" が、いくつかの方法を提案していただけますか?

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

[編集]私は以下を行いました。nullに戻ります。

            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())は、Element が返される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 に答える