我有一个计划以后序方式遍历 dom 树,然后当它遍历每个深度的兄弟姐妹时,对于每个兄弟组,我想获取它的文本内容中的元素数量。为了清楚起见,让我们看一个例子:
<?xml version="1.0" encoding="UTF-8"?>
<title text="title1">
<comment1 id="comment1">
<data1> this is an example</data1>
<data2> this example tries to do a demo over a dom tree</data2>
</comment1>
<comment2 id="comment2">
<data3> while it' beeing traversing in postorder fashion </data3>
<data4> hope it works! </data4>
<data5> :) </data5>
</comment2>
</title>
例如,我想找出 data 1 和 data2 的字符数以及 data3-5 togetehr 的字符数。这是我到目前为止编写的用于遍历树并计算 TFIDF 值的代码,但正如我所提到的,我想分别找到每组兄弟姐妹的 TF,有什么线索吗?提前致谢
lass tree{
private static int total=0;
private static double tf=0;
private static double result=0;
private static double TFIDFresult = 0;
static double TFIDF(int wordcount,String segment,String keyword)
{
if(segment==null)
return TFIDFresult;
StringTokenizer tokenizer =new StringTokenizer(segment) ;
while(tokenizer.hasMoreTokens()){
total++;
if( tokenizer.nextToken().equals(keyword))
wordcount++;
tf= (double) wordcount / total;
double inverseTF = Math.log10((float) wordcount / 4);
TFIDFresult = (((double) wordcount / total * inverseTF ));
}
return TFIDFresult;
}
public static void check(Node node){
if (node == null || node.getNodeName() == null)
return;
result= TFIDF(total, node.getNodeValue(), "this");
check(node.getFirstChild());
System.out.println(node.getNodeValue() != null && node.getNodeValue().trim().length() == 0 ? "" : node);
check(node.getNextSibling());
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
File file = new File("d:\\a.xml");
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
Node b=document.getFirstChild();
check(b);
System.out.println(result);
}
}
ps:出于某种原因,我手动假设计算中的文档数为4。