2014-02-11 34 views
0

從文件顯示互聯網上的信息幫助,有一個文件,該文件是在一個類似的聯繫http://url.com/info.xsl如何在TextView中

它具有以下結構:

<data> 
     <Connections/> 
      <Current_Listeners>3</Current_Listeners> 
      <Description/> 
      <Currently_Playing> 
        <Name>Black Sun Empire - Salvador (Feat. Bless)</Name> 
      </Currently_Playing> 
      <Source/> 
     <Connections/> 
     <Current_Listeners>0</Current_Listeners> 
     <Description/> 
      <Currently_Playing> 
        <Name>Black Sun Empire - Salvador (Feat. Bless)</Name> 
      </Currently_Playing> 
     <Source/> 
</data> 

我怎樣才能閱讀該文件從標籤之間的框中選擇信息,並將其顯示在我的TextView中。

+0

ü意味着ü希望讀取特定節點並在textview中顯示??? –

+0

您可以使用xml解析 – Piyush

+0

我想讀取標籤之間的一行並顯示它 – user3064772

回答

2

你可以嘗試這樣的事情:

  // Get your file from internet 
    URL url = new URL("http://url.com/info.xsl"); 
    URLConnection connection = url.openConnection(); 
    InputStream in = connection.getInputStream(); 
    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/filename.xml" 
    File file = new File (filePath); 

    CreateFileFromInputStream(in, filePath) ; 

      // Parse it with document builder factory 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = null; 
    dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = null; 
    doc = dBuilder.parse(file); 
    doc.getDocumentElement().normalize(); 
    // The root element is 
    doc.getDocumentElement().getNodeName(); 

    NodeList nList = doc.getElementsByTagName("Name"); 

    for (int i = 0 ; i < nList.getLength() ; i++) { 

     Element element = (Element) nList.item(i) ; 
     String name = getCharacterDataFromElement(element); 

    } 

有:

public static String getCharacterDataFromElement(Element e) 
{ 
    Node node = e.getFirstChild(); 
    if (node instanceof CharacterData) 
    { 
     CharacterData cd = (CharacterData) node; 
     return cd.getData(); 
    } 
    return ""; 
} 

和:

public void CreateFileFromInputStream(InputStream inStream, String path) throws IOException { 
    // write the inputStream to a FileOutputStream 
    OutputStream out = new FileOutputStream(new File(path)); 

    int read = 0; 
    byte[] bytes = new byte[1024]; 

    while ((read = inStream.read(bytes)) != -1) { 
     out.write(bytes, 0, read); 
    } 

    inStream.close(); 
    out.flush(); 
    out.close(); 

} 

我希望它可以幫助...

+0

非常感謝你,我會嘗試 – user3064772

+1

只能迭代一個數組或一個java.lang.Iterable的實例在nList這裏顯示爲(Node節點:nList){ – user3064772

+0

好吧,我不記得NodeList是不可迭代的。我編輯了我的問題,我替換了foreach的一個爲 –