要素を解析しようとしましたが、成功しませんでした。このコードを実行すると、デバッグ用の印刷メソッドで「null」が出力されます。これは、要素が見つからなかったことを意味します。
送信される配列は文のリストです。各パターンは正規表現パターンです。私がやろうとしているのは、文がパターンに一致するかどうかを検索することです。含まれている場合は、複数のテンプレートからテンプレートを選択し、そうでない場合は新しいエントリを作成します。以下のコードが機能しないため、新しいエントリの作成を実装していません。
ところで、ノード自体ではなく、ノードのコンテンツが null のように見えます。
for (int i = 0; i < sents.length; i++) {
for (int i1 = 0; i1 < categories.getLength(); i1++) {
Element root = parser.document.getDocumentElement();
NodeList categories = root.getChildNodes();
category = (Element) categories.item(i1);
pattern = category.getElementsByTagName("pattern").item(0);
if (pattern != null) {
System.out.println(pattern.getNodeValue());
}
else {
System.out.println("Pattern object is null.");
}
Pattern regex = Pattern.compile(pattern.getNodeValue());
Matcher matcher = regex.matcher(sents[i]);
if (matcher.matches()) { // If current sentence matches
matches = true;
break;
}
}
if (matches) { // If found
templates = category.getElementsByTagName("template");
int chosen = Generator.generateInt(0,templates.getLength()-1); // Another class method tht generates an integer between 0 and templates.getLength()-1, note that the lower range and upper range are both inclusive.
Node template = templates.item(chosen);
System.out.println(template.getNodeValue());
}
}
変数パーサーはクラス XMLparser に割り当てられます。XMLparser のコードは次のとおりです。
public XMLparser(String name) {
document = getDocument(name);
}
protected static Document getDocument(String name) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(name));
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void saveFile(String name) {
try {
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(name+".xml"));
transformer.transform(source, result);
System.out.println("File saved!");
}
catch (Exception e) { e.printStackTrace(); }
}
XML ファイルは次のとおりです。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE categories SYSTEM "vocab.dtd">
<categories>
<category>
<pattern>WHAT IS YOUR NAME</pattern>
<template>My name is JavaBot.</template>
</category>
</categories>
そして dtd ファイル:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT categories (category*)>
<!ELEMENT category (pattern, template*)>
<!ELEMENT pattern (#PCDATA)>
<!ELEMENT template (#PCDATA)>