0

重複の可能性:
Javaを使用してXMLの要素値を取得する方法は?

dom を使用して Java で xml ファイルを解析しようとしています。xml は次のようになります。

<documents>
  <document>
    <element name="doctype">
      <value>Circular</value>
    </element>
  </document>
</documents>

ルート ノード「ドキュメント」と子ノード「ドキュメント」を取得するのは簡単です。しかし、「doctype」という名前の要素の値を取得できません (値「Circular」をデータベースに保存したい)。誰か助けてくれませんか?

4

1 に答える 1

1

次の XPath を使用して、探しているデータを取得できます。

/documents/document/element[@name='doctype']/value

デモ

次のデモ コードは、DOM に対してその XPath を実行する方法を示しています。このアプリケーションは、標準の Java SE 5 (またはそれ以降) のインストールで実行されます。

package forum11578831;

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document dDoc = builder.parse("src/forum11578831/input.xml");

        XPath xPath = XPathFactory.newInstance().newXPath();
        String string = (String) xPath.evaluate("/documents/document/element[@name='doctype']/value", dDoc, XPathConstants.STRING);
        System.out.println(string);
    }

}

入力.xml

XPath が機能することを示すために、他の値を持つ属性を持つelement要素を含むように XML ドキュメントを拡張しました。namedoctype

<documents>
  <document>
    <element name="foo">
      <value>FOO</value>
    </element>
    <element name="doctype">
      <value>Circular</value>
    </element>
    <element name="bar">
      <value>BAR</value>
    </element>
  </document>
</documents>

出力

XPath を実行した結果は、まさにString探しているものです。

Circular
于 2012-07-20T13:03:46.713 に答える