[英]Don't understand result of java program
我想為另一個應用程序研究此代碼。 但我對“字符”有疑問。 這里的代碼:
package tp1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author jgmorenof
*/
class DeathOf extends DefaultHandler {
String node = null;
String contenu = null;
String titre = null;
String motif = "death of";
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
node = qName;
if (node.equals("title") || node.equals("text")) {
contenu = "";
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (node != null && node.equals("title")) {
//System.out.println(contenu);
titre = contenu;
//System.out.println("\t\tTitre : " + titre);
}
if (node != null && node.equals("text")){
annotate(contenu);
}
node = null;
contenu = null;
}
public void characters(char[] ch, int start, int length) {
if (node != null && (node.equals("title") || node.equals("text"))) {
contenu += new String(ch, start, length);
System.out.println(contenu);
}
}
public static void main(String[] args) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse("simplewiki-20161001-pages-articles.xml", new DeathOf());
} catch (Exception e) {
e.printStackTrace();
}
}
private void annotate(String contenu) {
String pattern = motif+" [A-Z][a-zA-Z_0-9]+ [A-Z][a-zA-Z_0-9]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(contenu);
if (m.find( )) {
for(int i=0;i<=m.groupCount();i++)
System.out.println("Personne: " + m.group(i).replace(motif,"") );
}
}
}
我不明白“system.out.println(contenu)”之后“字符”的結果。 我對 SAX 也不舒服。 任何人都可以向我解釋公共無效字符嗎? 為什么 contenu 不再是 ampty 了? 'ch, start, lentgh' 來自哪里?
因此,首先,SAX 解析器通過在您的類中調用方法來工作。 這就是該類實現 DefaultHandler 接口的原因。
因此,SAX 解析器在執行其工作時會調用這些公共方法startElement 、 endElement和字符!
你知道,你寫了這些方法,所以你應該知道它們在做什么!
但是很好:
public void characters(char[] ch, int start, int length) {
如前所述:SAX 解析器實現正在調用該方法 - 它正在使用與您的 XML 文件的內容相對應的值!
然后:
if (node != null && (node.equals("title") || node.equals("text"))) {
contenu += new String(ch, start, length);
以上創建了一個新的 String 值......並將其附加到contenu 。
換句話說:該字段contenu更改...因為代碼說它應該更改。
說真的:如果你不了解這些基本的東西; 那就先別搞XML解析了。 相反,退一步學習 Java 的基礎知識。
如果您想了解正在發生的事情:只需在每個公共方法中放置打印語句(也打印給每個方法的參數)……您將很快看到按什么順序和使用什么參數SAX 解析器正在調用這些方法!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.