2013-01-04 28 views
9

我有一個XML格式的字符串。我想閱讀它並獲取元素的值。以xml格式讀取字符串並獲取java中元素的值

我試過了Java JAXBContext unmarshell here。但是這需要創建對我來說不是必需的課程。

字符串:

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

我想獲得的年齡和名字的值。

任何人都可以幫助我。

+0

[如何使用Java檢索XML元素值?](http://stackoverflow.com/questions/4076910/how-to-retrieve-element-value-of-xml-using-java) –

回答

26

這是一個很好的支持你的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(); 
+0

感謝您的回覆 – Patan

+0

不客氣 – vault

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"));   
} 
3

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()) 
4

標準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); 
0

就像用更復雜的用戶個XML珍聞,和我一樣。如果你有相同名稱的元素,但是,不同的屬性,例如:

<field tag="8"> Country </field> 
<field tag="12"> State </field> 

提取它們的方法是,關注@保管庫的answer但是,要確保在.item(int)功能更改值。

如果您想要使用第一個字段.item(0)。如果你想要第二個你使用.item(1)

希望這有助於未來的用戶,因爲它爲我做。