2013-10-14 74 views
0

我想解析通過如下結構的XML文件。我試圖實現的是將其轉換爲MySQL中使用的表格格式。因此,例如,在這種情況下,我有一個這樣的表列格式與下面的示例行:如何將此XML文件解析到MySQL表中?

name | industry_permid | trbc_code | mnemonic 
Juvenile Products & Accessories | 4294951612 | 5320501015 | NULL 
Life & Health Insurance | 4294952862 | 55301030| LINS 

我的XML文件:

<conceptSet> 
    <concept> 
     <conceptId qcode="B:1389" /> 
     <type qcode="cptType:2" /> 
     <sameAs qcode="P:4294951612" /> 
     <name role="nameRole:main" xml:lang="en">Juvenile Products & Accessories</name> 
     <broader qcode="B:199" /> 
     <rtr:stage current="stg:live" /> 
     <sameAs qcode="TRBC-2012-Hierarchical-ID:5320501015" /> 
    </concept> 
    <concept> 
     <conceptId qcode="B:139" /> 
     <type qcode="cptType:2" /> 
     <sameAs qcode="P:4294952862" /> 
     <name role="nameRole:mnemonic" xml:lang="en">LINS</name> 
     <name role="nameRole:main" xml:lang="en">Life & Health Insurance</name> 
     <broader qcode="B:136" /> 
     <rtr:stage current="stg:live" /> 
     <sameAs qcode="TRBC-2012-Hierarchical-ID:55301030" /> 
    </concept> 
</conceptSet> 

的問題是每當我嘗試訪問這個XML樹中的元素,我只能得到具有名稱標籤的元素。我不知道如何訪問沒有任何標籤,如qcode和東西的元素。如果有任何幫助,我使用默認的Java XML解析器。

這是我到目前爲止的代碼,每次嘗試獲取屬性時都會輸出null。

File mapping = new File("blah.xml"); 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = dBuilder.parse(mapping); 
    doc.getDocumentElement().normalize(); 

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

    for (int i = 0; i < nodeList.getLength(); i++) { 
     System.out.println(nodeList.item(i).getAttributes().getNamedItem("qcode")); 
    } 

回答

1

在你for -loop,nodeList.item(i)concept元素。因此,您試圖從concept元素中檢索qcode屬性,該元素沒有。

您可以在concept元素的子節點重複,以獲得您所需要的元素,f.e:

for (int i = 0; i < nodeList.getLength(); i++) { 
    NodeList children = nodeList.item(i).getChildNodes(); 
    for (int j = 0; j < children.getLength(); j ++) { 
     System.out.println(children.item(i).getAttributes().getNamedItem("qcode")); 
    } 
} 

或者你可以檢索你需要直接使用XPath的節點,見this answer,例如。