2013-05-17 119 views
1

我在解析Java(Android)中的XML文件時遇到了一個小問題。如何從Java中的XML節點獲取標記「名稱」(Android)

我有一個XML文件,該文件是這樣的:

<Events> 
    <Event Name="Olympus Has Fallen"> 
    ... 
    </Event> 
    <Event Name="Iron Man 3"> 
    ... 
    </Event> 
</Events> 

我已經設法這樣做是爲了得到節點列表:

URL url = new URL("********"); 

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(new InputSource(url.openStream())); 
doc.getDocumentElement().normalize(); 

NodeList nodeList = doc.getElementsByTagName("Event"); 

而且我設法節點列表的每一個項目通過這樣做:

for (int i = 0; i < nodeList.getLength(); i++) { 
    // Item 
    Node node = nodeList.item(i); 
    Log.i("film", node.getNodeName()); 
} 

但是,這只是日誌:「事件」,而不是名稱標記的值。 如何從XML中輸出這個'name'標記的值。

任何人都可以幫我這個嗎? 在此先感謝!

+0

也許這個問題可以幫助你.. [閱讀xml在android] [1] [1]:http://stackoverflow.com/questions/9464087/how-to-read-xml-file-in-android – 2013-05-17 08:35:10

回答

6

但是,這只是日誌:「事件」而不是名稱標記的值。

是的,因爲你問的元素的名稱。沒有一個Name「標籤」 - 有一個Name屬性,這就是你應該找什麼:

// Only check in elements, and only those which actually have attributes. 
if (node.hasAttributes()) { 
    NamedNodeMap attributes = node.getAttributes(); 
    Node nameAttribute = attributes.getNamedItem("Name"); 
    if (nameAttribute != null) { 
     System.out.println("Name attribute: " + nameAttribute.getTextContent()); 
    } 
} 

(要在術語準確是非常重要的 - 這是值得了解的節點之間的差異,要素,屬性等等。它會幫助你在與他人溝通時以及在尋找正確的API位時呼叫。)

+0

Log.i(「nodetitle」,nodeList.item(0).getAttributes( ).getNamedItem( 「名稱」)getNodeValue())。這對我有效。非常感謝你! –

相關問題