私の質問は、親要素の「孫」と同じ名前の他の要素がある場合、特定の親要素のすぐ下に要素を取得するにはどうすればよいですか。
Java DOMライブラリを使用してXML要素を解析していますが、問題が発生しています。これが私が使用しているxmlのいくつか(ごく一部)です:
<notifications>
<notification>
<groups>
<group name="zip-group.zip" zip="true">
<file location="C:\valid\directory\" />
<file location="C:\another\valid\file.doc" />
<file location="C:\valid\file\here.txt" />
</group>
</groups>
<file location="C:\valid\file.txt" />
<file location="C:\valid\file.xml" />
<file location="C:\valid\file.doc" />
</notification>
</notifications>
<file>
ご覧のとおり、要素を配置できる場所は2つあります。グループ内またはグループ外のいずれか。よりユーザーフレンドリーなので、このように構造化してほしいと思います。
さて、私がそれを呼ぶときはいつでも、それは私に要素の下のものを含むnotificationElement.getElementsByTagName("file");
すべての要素を与えます。私はこれらの種類のファイルをそれぞれ異なる方法で処理するため、この機能は望ましくありません。<file>
<group>
私は2つの解決策を考えました:
- ファイル要素の親要素を取得し、それに応じて処理します(それがである
<notification>
か。であるかによって異なります)<group>
。 <file>
混乱を避けるために、2番目の要素の名前を変更します。
<file>
これらのソリューションはどちらも、物事をそのままにして、要素の直接の子である要素のみを取得するほど望ましいものではありません<notification>
。
私はこれを行うための「最良の」方法についてのIMPOのコメントと回答を受け入れていますが、このプロジェクトの残りの部分で使用されているDOMソリューションに本当に興味があります。ありがとう。