读取XML文件

时间:2014-03-24 11:46:01

标签: android xml

我使用以下代码来读取我在C:目录中的ResourceFile中保存的名为ContactFile的XML文件

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        extract(null);
    }

    public static void extract(String argv[])
    {     
        try
        {
            File XmlFile = new File("C:\\ResourceFile\\ContactFile.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(XmlFile);
            doc.getDocumentElement().normalize();     
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("ExtractContact");
            System.out.println("----------------------------");  

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                System.out.println("\nCurrent Element :" + nNode.getNodeName());     
                if (nNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element eElement = (Element) nNode;
                    System.out.println("id : " + eElement.getAttribute("id"));
                    System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
                    System.out.println("Phone Number : " + eElement.getElementsByTagName("phoneNumber").item(0).getTextContent());
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}   

XML文件具有以下形式:

 <Document>
    <ExtractContact>
        <id></id>
        <name></name>
        <phoneNumber />
    </ExtractContact>
</Document>

我收到此错误:

  

E / Trace(1596):错误打开跟踪文件:没有这样的文件或目录(2)

3 个答案:

答案 0 :(得分:0)

我不确定你在android中使用的是什么

File XmlFile = new File("C:\\ResourceFile\\ContactFile.xml");

请将您的文件保存在资产文件夹中,而不是从那里获取文件!

按如下方式进行

InputStream is = getResources().getAssets().open("ContactFile.xml");
String result= convertStreamToString(is);

以字符串形式获取文件,我们可以编写convertStreamToString方法,如下所示

public static String convertStreamToString(InputStream is)
            throws IOException {
            Writer writer = new StringWriter();
        char[] buffer = new char[2048];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        String text = writer.toString();
        return text;
}

如果文件在SD卡中,则读取如下

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

答案 1 :(得分:0)

Here您可以找到如何从资产中读取文件。

here如何从原始

中读取

答案 2 :(得分:0)

我刚刚将文件的路径更改为“Environment.getExternalStorageDirectory(),ContactFile.xml”。

现在就是:File XmlFile = new File(Environment.getExternalStorageDirectory(),“newfile / contactFile / ContactFile.xml”);

现在可行。