3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java SAXParserでXMLをパースするためにやったこと

3
Posted at

事象

社内ネットワーク上で、Javaのjavax.xml.parsers.SAXParserを使ってXMLをパースしたかった。
以下、2点ちょっとはまった。

  1. SAXParserがDTDの検証のためにインターネットに接続しようとしてこける
  2. XMLコメントの内容をパースしたかったがうまく取れなかった

パースしたかったファイルはiBatisで定義されたSqlMapファイル。

対応

1.SAXParserがインターネットにつながらないとき向けの対応

// パーサファクトリの初期化 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); // saxParserがDTDの検証のためにインターネットに接続するのを抑止する。 saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

この記述でSAXParserがネットワークに接続しようとするのを抑止した。

2.XMLコメントの内容をパースしたい向けの対応

CustomHandler handler = new CustomHandler(); SAXParser saxParser = saxParserFactory.newSAXParser(); // (によるxmlコメントを読み込むために設定) saxParser.getXMLReader().setProperty("http://xml.org/sax/properties/lexical-handler", handler); これで、CustomHandler#commentが呼ばれるようになり、コメント文もパース可能になる。

以上。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?