有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将文本文件转换为xml

我想把text file转换成xml file。我有大量的字符串,但我不想直接用xml编写

因此,我已经做了一个文本文件,现在我想转换这个

将文本文件转换为xml格式,但运行此文件时没有输出。这是我的

代码:

public void convert() throws Exception {

 String text[]=new String[10];

 FileOutputStream fout = new FileOutputStream("res/values/mysml.xml");

 OutputStreamWriter out = new OutputStreamWriter(fout);  

 InputStream in= getAssets().open("myText.txt");

 Scanner scn = new Scanner(is);

for(int i=0;i<10;i++)

text[i]=bin.readLine();

out.write("<?xml version=\"1.0\"?>\r\n");  

out.write("<resources>\r\n");  

for (int i = 0; i < 10; i++){

out.write("<item>"+text[i]+"</item>");

}

out.write("</resources>");

out.flush();

out.close();

}


共 (6) 个答案

  1. # 1 楼答案

    http://www.xml-sitemaps.com/检查你的网站

    在滚动窗口中进行更改,比如在子文件夹中添加html文件。把你已经看到的编码放进去

    不要从网页中保存XML文件。它将在窗口中为您提供未更改的代码

    从滚动窗口复制文本。将其粘贴到空白记事本页面中

    另存为“sitemap.xml”

    记住,将引号保存为xml文件

  2. # 2 楼答案

    试试看

    BufferedReader reader=new BufferedReader(new InputStreamReader(in));
    
    String line=null;
    out.write("<?xml version=\"1.0\"?>\r\n");  
    out.write("<resources>\r\n");  
    while((line=reader.readLine())!=null)
    {
      out.write("<item>"+line+"</item>");
    }
    out.write("</resources>");
    out.close();
    
  3. # 3 楼答案

    据我所知,您希望在运行时在应用程序的res/values/文件夹中动态创建一个xml。我认为这是不可能的,因为你在应用程序的资源中只有读取权限。不要将xml存储到res文件夹中,而是尝试使用内部或外部memmory。有关android存储选项的更多信息,请参见here

  4. # 4 楼答案

    for(int i=0;i<10;i++){
        text[i]=bin.readLine();
    } <-----
    
    out.write("<?xml version=\"1.0\"?>\r\n");  
    
    out.write("<resources>\r\n"); 
    
    
    
    for (int i = 0; i < 10; i++){
        out.write("<item>"+text[i]+"</item>");
    }
    
  5. # 5 楼答案

    如果你有这样做,请使用StAX。你可以用一种更简单的方式打开关闭标签,而作者也会处理你的文件

    XMLOutputFactory output = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = output.createXMLStreamWriter(new BufferedWriter(new FileWriter(new File(FILE_PATH))));
    writer.writeStartDocument("UTF-8","1.0");
    // Write Whatever file you have as string
    writer.flush();
    writer.close();
    

    StAX搭载JDK 1.6

  6. # 6 楼答案

    要刷新到流,请在此处添加此行:

    out.write("</resources>");
    //line
    out.flush();
    
    out.close();