XPath在<random>标签内获取<li>

时间:2017-06-27 03:08:04

标签: java xpath netbeans

snapshot of aiml file || code snippet

我正在尝试使用DOM Parser + XPath解析这个.aiml文件,但我不能/不确定如何在随机标记内获取li文本,代码片段是我到目前为止,任何帮助赞赏。我对此仍然很新。

.aiml文件

<category>
<pattern>100 *</pattern><that>HOW MUCH *</that>
<template>Wow that is <random>
<li>expensive.</li>
<li>a lot of money.</li>
<li>more than I have.</li>
</random>
</template></category>

代码

String expression = "/aiml/category";

NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);


for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
System.out.println("\nCurrent Element :" + nNode.getNodeName()); //this returns <category>

            if ((nNode.getNodeType() == Node.ELEMENT_NODE)) {
                Element eElement = (Element) nNode;
String question = eElement.getElementsByTagName("pattern").item(0).getTextContent();
String answer = eElement.getElementsByTagName("template").item(0).getTextContent();

                System.out.println("Question : " + question);
                System.out.println("Answer : " + answer);
   }
}

1 个答案:

答案 0 :(得分:0)

要获取li元素文本内容,您可以使用以下代码:

InputSource inputSource = new InputSource( new FileInputStream( new File("category.aiml") ) ) ;
  Object li = xpath.evaluate("//category/template/random/li", inputSource, XPathConstants.NODESET);
 List<String> liElements = new ArrayList<>();
  if ( li != null )
  {

        NodeList liNodes = (NodeList)li;
        for ( int i = 0; i < liNodes.getLength(); i++ )
        {
            liElements.add( liNodes.item(i).getTextContent() );
        }
   }

使用javax.xml.xpathevaluate 代码//category/template/random/li中的xpath将该路径上的节点作为NODESET。 迭代节点并调用getTextContent()以获取每个li的文本。