2013-04-09 217 views
1

我正在開發一個Java類來解析這個XML文件:XML解析。試圖讓屬性

<document src="xmls/sections/modules/200_1.xml"> 
<module name="product_info" id="1"> 
    <product_primary_id>200</product_primary_id> 
    <product_section_id>1</product_section_id> 
    <product_section_item_id></product_section_item_id> 

    <type>1</type> 
    <position>1</position> 
    <align>top</align> 

    <url href="productview/info.html"></url> 
</module> 
</document> 

而且我有這個java類:

try { 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = dBuilder.parse(contingut); 
    doc.getDocumentElement().normalize(); 
    //loop a cada module 
    NodeList nodes = doc.getElementsByTagName("module"); 
    for (int i = 0; i < nodes.getLength(); i++) { 
     Node node = nodes.item(i); 
     Element element = (Element) node; 
     if(element.getNodeType() == Element.ELEMENT_NODE){ 
      Log.d("debugging","product_primary_id: "+getValue("product_primary_id",element)); 
      Log.d("debugging","product_section_id: "+getValue("product_section_id",element)); 
      //Log.d("debugging","product_section_item_id: "+getValue("product_section_item_id",element)); 
      Log.d("debugging","type: "+getValue("type",element)); 
      Log.d("debugging","position: "+getValue("position",element)); 
      Log.d("debugging","align: "+getValue("align",element)); 
      //Log.d("debugging","url: "+getValue("url",element)); 
     } 
    } 
} catch (Exception e){ 
      e.printStackTrace(); 
} 

正如你可以看到,它的循環,每「模塊」標籤並獲取其子值。但我需要模塊的名稱屬性,但因爲它是一個NodeList,不能使用方法getAttribute("name");

任何想法?

回答

2

你可以做

Element element = (Element) node; 
element.getAttribute("name") 

檢索name atttribute爲代表module標籤的節點。您可以這樣做,因爲module標籤本身也是一個元素。 getAttribute()方法記錄爲here

+0

該死的,沒想到。謝謝! – Reinherd 2013-04-09 08:41:02