LoginSignup
3
5

More than 5 years have passed since last update.

java DocumentBuilderのparse解析でハマったこと

Posted at

javaでxmlを解析したいと思いまして、DocumentBuilderを使って以下のコードを書きました。
ネットでもよく見るコードなのですが、

// ドキュメントビルダーファクトリを生成
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
// ドキュメントビルダーを生成
DocumentBuilder builder = dbfactory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

xmlのデータはxml.getBytes()で正常に取得できていたので、
後はdocを解析して対象のタグを抽出するだけなのですが、
試しに、docそのものを出力したところコンソールにnullとの記載が。 :scream:

docに何も入っていないと勘違いしてしまい、builder.parseが正常に動作してないと疑ってしまいましたが、
実はdocの出力の仕方がまずかっただけで、正しくxmlをparseできていました。
Document docの後に、

Element root = doc.getDocumentElement();
NodeList list = root.getElementsByTagName("タグ名");
とすればxmlの解析情報が入っていました。

この事実にすぐに気がつけず無駄な時間を費やしてしまった。反省です。 :sweat_smile:

3
5
1

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
5