2016-10-23 98 views
0

它已經閱讀了大量關於閱讀XML的文章,但幾乎所有文章都在閱讀完整文檔並將其打印出來。XML:直接獲取XML元素

,但我想獲得一個特定的內容..

<bookstore> 
<book category="cooking"> 
    <title lang="en">Everyday Italian</title> 
    <author>Giada De Laurentis</author> 
    <year>2005</year> 
    <price>30.00</price> 
</book> 
<book category="children"> 
    <title lang="es">Harry Potter and the Half-Blood Prince</title> 
    <author>J. K. Rowling</author> 
    <year>2005</year> 
    <price>29.99</price> 
</book> 

這裏作爲類別讀出一個例子=兒童作家= J.K的內容:羅琳。

是可能的,是的有人的代碼?

感謝

+0

請修改您的文章更正語言錯誤,並嘗試用你的問題描述更清楚 - 否則人們很難理解。 – user905686

+1

在XPath上進行閱讀。它用於查詢XML文檔。 – kaqqao

+0

謝謝。我會尋找...... –

回答

1

事實上,使用XPath,你可以很容易地檢索類別=「孩子」的值作者。

沒有測試解決方案,但你有這個想法(我已經前綴一些軟件包來指導你在XPATH一些簡單的類名其他包存在,以解決其他需要):

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = builderFactory.newDocumentBuilder(); 

    org.w3c.dom.Document document = builder.parse(yourXmlFile); 
    XPath xpath = XPathFactory.newInstance().newXPath(); 

    org.w3c.dom.Node authorNode= (Node) xpath.evaluate("//book[@category='children']/author", document, 
     XPathConstants.NODE); 
    String author= authorNode.getTextContent();