2012-12-05 5 views
1

나는 안드로이드에서 xml 파일을 읽는 것을 처음으로 읽었습니다. 나는 이것을 위해 구글을 찾았지만 적절한 해결책을 얻을 수 없었다.android에서 xml 파일 읽기 - 구문 분석

는 난 다음 correspondance에 얻을 목적으로, 분석 한 결과,이 XML 파일을

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
     <key>aaaa</key> 
     <array> 
       <string>b</string> 
       <string>c</string> 
       <string>d</string> 
       <string>e</string> 
       <string>f</string> 
     </array> 
     <key>bbbb</key> 
     <array> 
       <string>g</string> 
       <string>h</string> 
       <string>i</string> 
       <string>j</string> 
       <string>k</string> 
     </array> 
</dict> 
</plist> 

파싱 목적 :

AAAA를 [B, C, D, E, F] ->리스트/어레이

BBBB [G, H, I, J, K는] -> 환언리스트/배열

, 모든 문자열 (키)가 그 키의 내부 문자열의 배열에 대응한다.

어떻게해야합니까? 또한 xml 파일을 어디에 배치해야하는지 알고 싶습니다. (네, 다음 무슨 일이 파일의 주소 될 경우 고해상도/원시/폴더에 있습니까?)

+0

http://developer.android.com/training/basics/network-ops/xml.html .. XML 파싱 – stinepike

+1

에 대한 좋은 튜토리얼 http://www.javacodegeeks.com, 희망이 도움이 /2012/01/xml-parsing-using-saxparser-with.html도 goo 자습서입니다. –

답변

2

스스로 그렇게하는 첫 번째 무승부 :

public final class XMLManager { 


public static HashMap<String, ArrayList<String>> getHmPlist(){ 

    HashMap<String, ArrayList<String>> hmPlist = null; 

    try { 


     hmPlist = new HashMap<>(); 
     Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("D:\\Loic_Workspace\\Test2\\res\\test.xml")); 
     NodeList ndList = doc.getElementsByTagName("key"); 
     Integer keyLength = ndList.getLength(); 
     String keyValue = null; 
     NodeList ndArray = null; 
     Integer ndArrayLength = null; 
     ArrayList<String> alElement = null; 

     for(int i=0;i<keyLength;i++){ 
      alElement = new ArrayList<>(); 
      keyValue = ndList.item(i).getTextContent(); 
      if(keyValue != null){ 
       ndArray = ndList.item(i).getNextSibling().getNextSibling().getChildNodes(); 
       ndArrayLength = ndArray.getLength(); 
       for(int j=0;j<ndArrayLength;j++){ 

        if(ndArray.item(j).getNodeName().equalsIgnoreCase("string")){ 
         alElement.add(ndArray.item(j).getFirstChild().getTextContent()); 
        } 

       } 

       hmPlist.put(keyValue, alElement); 

      } 

     } 


    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (SAXException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ParserConfigurationException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return hmPlist; 

} 



} 

anserw하기 위해서 res/raw/folder에 관한 질문. 예, XML을 폴더에 넣고 R 클래스를 통해 Java 코드에 사용해야합니다.