XML形式の文字列があります。それを読んで、要素の値を取得したいと思います。
Java JAXBContext unmarshellを試しましたが、これには必要のないクラスの作成が必要です。
弦:
<customer>
<age>35</age>
<name>aaa</name>
</customer>
年齢と名前の値を取得したい。
XML形式の文字列があります。それを読んで、要素の値を取得したいと思います。
Java JAXBContext unmarshellを試しましたが、これには必要のないクラスの作成が必要です。
弦:
<customer>
<age>35</age>
<name>aaa</name>
</customer>
年齢と名前の値を取得したい。
これはあなたのxmlです:
String xml = "<customer><age>35</age><name>aaa</name></customer>";
そして、これはパーサーです:
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(xml));
Document doc = builder.parse(src);
String age = doc.getElementsByTagName("age").item(0).getTextContent();
String name = doc.getElementsByTagName("name").item(0).getTextContent();
JSoupは XML を適切にサポートしています
import org.jsoup.*
import org.jsoup.nodes.*
import org.jsoup.parser.*
//str is the xml string
String str = "<customer><age>35</age><name>aaa</name></customer>"
Document doc = Jsoup.parse(str, "", Parser.xmlParser());
System.out.println(doc.select("age").text())
標準APIでのXPathの使用:
String xml = "<customer>" + "<age>35</age>" + "<name>aaa</name>"
+ "</customer>";
InputSource source = new InputSource(new StringReader(xml));
XPath xpath = XPathFactory.newInstance()
.newXPath();
Object customer = xpath.evaluate("/customer", source, XPathConstants.NODE);
String age = xpath.evaluate("age", customer);
String name = xpath.evaluate("name", customer);
System.out.println(age + " " + name);
JDOMは非常に使いやすいです。
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("c:\\file.xml");
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
List list = rootNode.getChildren("customer");
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
System.out.println("Age : " + node.getChildText("age"));
System.out.println("Name : " + node.getChildText("name"));
}