15

XML形式の文字列があります。それを読んで、要素の値を取得したいと思います。

Java JAXBContext unmarshellを試しましたが、これには必要のないクラスの作成が必要です。

弦:

<customer>
    <age>35</age>
    <name>aaa</name>
</customer>

年齢名前の値を取得したい。

4

6 に答える 6

49

これはあなたの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();
于 2013-01-04T14:43:08.670 に答える
9

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())
于 2013-01-04T14:43:01.557 に答える
7

標準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);
于 2013-01-04T14:47:33.957 に答える
2

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"));         
}
于 2013-01-04T14:40:06.210 に答える