634 - JAXP - DOM - 指定した要素の属性を取得AdvertisementgetAttribute
指定した要素の属性を取得するためには、ElementクラスのgetAttributeメソッドを利用します。利用例を以下に示します。
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DOMTest {
public static void main(String[] args) {
try{
FileInputStream fis = new FileInputStream("./sample.xml");
BufferedInputStream bis = new BufferedInputStream(fis);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(bis);
// ルート要素の取得
Element root = doc.getDocumentElement();
// book 要素のリストを作成
NodeList list = root.getElementsByTagName("book");
// 1つ目の book 要素の id を表示
Element element = (Element)list.item(0);
System.out.println("1つ目のbook要素のid:" + element.getAttribute("id"));
}catch(Exception e){
System.err.println(e.getMessage());
System.exit(1);
}
}
}
入力ファイル(sample.xml)
<?xml version="1.0" encoding="Shift_JIS"?>
<document>
<book id="10">
<title>AAA</title>
<price>1500</price>
</book>
<book id="20">
<title>BBB</title>
<price>1200</price>
</book>
</document>
結果 1つ目のbook要素のid:10 Advertisement |
ショートカット・634・このカテゴリのトップページに戻る ・634labs UIコレクションギャラリー サイト検索Y!ログール |