如何在textview中显示Internet上文件的信息

时间:2014-02-11 12:47:06

标签: android

需要帮助,有一个类似链接http://url.com/info.xsl

的文档

它具有以下结构:

<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中。

1 个答案:

答案 0 :(得分: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);

    }

with:

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();

}

我希望它有所帮助...