2011-10-25 4 views
0

でカバーされたテキスト:各<テキスト>の各<文>について要素オフセットと私たちは、次のようなPCDATA要素を含むXMLファイルを処理する必要がdom4jの

<corpus id="c01"> 
    <text id="t01> 
    <sentence id="s01">Mary <instance id="i01">had</instance> a <instance id="i02">lamb</instance>.</sentence> 
    <sentence id="s02">...</sentence> 
    ... 
    </text> 
    ... 
</corpus> 

は、我々はデータ構造を移入する必要がありますセンテンスIDと、そのセンテンスによってカバーされる全文を含む。次に、それぞれ<インスタンス>に対して、インスタンスIDと、その文内の開始位置と終了位置を含むデータ構造を設定する必要があります。 (私たちは、空白が正規化されているかどうかを気にしない。)

だから、上記の例のために、私たちは基本的に必要な以下:

s.id = "s01" 
s.text = "Mary had a lamb." 
i1.id = "i01" 
i1.start = 6 
i1.end = 8 
i2.id = "i02" 
i2.start = 12 
i2.end = 15 

DOM4Jでこれを行うのいずれかの方法はありますか? Element.getText()メソッドは、子要素のテキストをスキップし、別の要素内の要素のオフセットを与えるメソッドは表示されません。 dom4jがこのタスクに適切でない場合、より良いツールは何ですか?

答えて

0

確かに実行可能ですが、少しの作業が必要です。ツリー内のどこにいるのかを追跡し、テキストとインスタンスのオフセットが進行するにつれてそれを蓄積するVisitorを作成することができます。しかし、その解決法はSAXハンドラで直接実装することもできますが、これははるかに高速です。

これは、で始まるに何か与える必要があります。

public class Main extends DefaultHandler { 

StringBuilder buf = new StringBuilder(); 
boolean collecting = false; 
int ic = 0; 

@Override 
public void startElement(String uri, String localName, String qName, 
     Attributes attributes) throws SAXException { 
    if (localName.equals("sentence")) { 
     System.out.printf("s.id=%s\n", attributes.getValue("id")); 
     collecting = true; 
     buf.setLength(0); 
     ic = 0; 
    } else if (localName.equals("instance")) { 
     ++ic; 
     System.out.printf("i%d.id=%s\n", ic, attributes.getValue("id")); 
     System.out.printf("i%d.start=%s\n", ic, buf.length()); 
    } 

} 

@Override 
public void endElement(String uri, String localName, String qName) 
     throws SAXException { 
    if (localName.equals("sentence")) { 
     collecting = false; 
     System.out.printf("s.text=%s\n", buf.toString()); 
    } else if (localName.equals("instance")) { 
     System.out.printf("i%d.end=%s\n", ic, buf.length()); 
    } 
} 

@Override 
public void characters(char[] ch, int start, int length) 
     throws SAXException { 
    if (collecting) { 
     buf.append(ch, start, length); 
    } 
} 

public static void main(String[] args) throws Exception { 

    SAXParserFactory f = SAXParserFactory.newInstance(); 
    f.setNamespaceAware(true); 
    f.newSAXParser().parse(Main.class.getResourceAsStream("data.xml"), 
      new Main()); 
} 
} 
関連する問題