使用XPath检索集合的正确方法?

时间:2010-10-07 00:42:20

标签: java xml

我有一个包含几个录音的xml文件,如下所示:

<audiolibrary>
    <prompt name="accountinfo">
        <prompt-segment>
            <audio src="audio/default/accountinfo.wav" 
                text="Account Information"/>
        </prompt-segment>
    </prompt>
    ...
    <prompt name="accountclosed">
        <prompt-segment>
            <audio src="audio/default/accountclosed.wav"
                text="Sorry, your account is closed."/>
        </prompt-segment>
    </prompt>
</audiolibrary>

在XPath教程之后,我知道我可以使用以下表达式检索第一个提示的属性:

xPathObject.compile("/audioibrary/prompt[@name='accountinfo']/prompt-segment/audiofile/@src");
xPathObject.compile("/audioibrary/prompt[1]/prompt-segment/audiofile/@src");

现在,如果我想要检索所有提示,我是否正确理解我应该遍历.compile()语句,直到我想出一个空白值?

像这个骨架的例子,这里?:

int index = 1;
do
{
    xPathObject.compile("/audioibrary/prompt["+ index +"]/prompt-segment/audiofile/@src");
    (Prompt content retrieval code here)
    index++;
}
while(!src.equals(""))

或者,有没有更好的方法来检索集合?

谢谢!
IVR Avenger

2 个答案:

答案 0 :(得分:4)

XPathExpression expr = xPathObject.compile("/audiolibrary/promp/prompt-segment/audio/@src")
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    //what you are going to do.... 
}

答案 1 :(得分:0)

一点点XPath,一点点递归:

String basePromptExpression = "/AudioLibrary/prompt";

NodeList nodes  = (NodeList) xPathObject.evaluate(basePromptExpression, promptInputSource, XPathConstants.NODESET);

for (int nodeIndex = 0; nodeIndex < nodes.getLength(); nodeIndex++)
{
    Node singleNode = nodes.item(nodeIndex);
    String promptName = singleNode.getAttributes().getNamedItem("name").getNodeValue();
    String promptSrc = findNode(singleNode, "audiofile").getAttributes().getNamedItem("src").getNodeValue();
    String promptText = findNode(singleNode, "audiofile").getAttributes().getNamedItem("text").getNodeValue();

    System.out.println("Name: "+promptName+" Src: "+promptSrc+" Text: "+promptText);
}


private static Node findNode(Node singleNode, String nodeName)
{
    Node namedNode=null;
    NodeList nodeChildren = singleNode.getChildNodes();
    Node childNode = null;

    for (int nodeIndex =0; nodeIndex < nodeChildren.getLength(); nodeIndex++)
    {
        childNode = nodeChildren.item(nodeIndex);

        if (childNode.hasChildNodes())
        {
            childNode = findNode(childNode, nodeName);
        }

        if (childNode.getNodeName().equals(nodeName))
        {
            namedNode = childNode;
            return namedNode;
        }
    }

    return namedNode;
}