Android 如何将新节点插入现有XML
我想在现有的xml文件中插入一个新节点,但下面的代码再次插入所有节点 如果文件存在,我将进行测试。如果没有,我将创建一个新的xml文件并编写标记。如果存在,它也会创建节点,但方式不对Android 如何将新节点插入现有XML,android,xml,Android,Xml,我想在现有的xml文件中插入一个新节点,但下面的代码再次插入所有节点 如果文件存在,我将进行测试。如果没有,我将创建一个新的xml文件并编写标记。如果存在,它也会创建节点,但方式不对 //create a new file called "new.xml" in the SD card File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/download/teste/audit.xml"); if (
//create a new file called "new.xml" in the SD card
File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/download/teste/audit.xml");
if (newxmlfile.exists()){
try{
fileos = new FileOutputStream(newxmlfile, true);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
} else {
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
}
//we create a XmlSerializer in order to write xml data
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(fileos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "root");
serializer.startTag(null, "child1");
serializer.endTag(null, "child1");
serializer.startTag(null, "child2");
serializer.attribute(null, "attribute", "value");
serializer.endTag(null, "child2");
serializer.startTag(null, "child3");
serializer.text("some text inside child3");
serializer.endTag(null, "child3");
serializer.endTag(null, "root");
serializer.endDocument();
serializer.flush();
fileos.close();
Context context = getApplicationContext();
CharSequence text = "Save!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
结果是:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
</root><?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
</root>
child3中的一些文本
child3中的一些文本
但我想要这样的结果:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
</root>
child3中的一些文本
child3中的一些文本
谢谢 看起来Android中没有这样的API。但是,您仍然可以使用以下选项来解决此问题:
- 寻找一些提供这种能力的开源库李>
- 仍然使用
执行一些手动字符串操作,如下所示:XmlSerializer
private void testXMLFiles() { //create a new file called "new.xml" in the SD card final File newXmlFile = new File(Environment.getExternalStorageDirectory() + "/download/teste/audit.xml"); RandomAccessFile randomAccessFile = null; final boolean fileExists = newXmlFile.exists(); String lastLine = null; if (fileExists) { try { randomAccessFile = new RandomAccessFile(newXmlFile, "rw"); randomAccessFile.seek(0); if (null != randomAccessFile) { final Scanner scanner = new Scanner(newXmlFile); int lastLineOffset = 0; int lastLineLength = 0; while (scanner.hasNextLine()) { // +1 is for end line symbol lastLine = scanner.nextLine(); lastLineLength = lastLine.length() + 2; lastLineOffset += lastLineLength; } // don't need last </root> line offset lastLineOffset -= lastLineLength; // got to string before last randomAccessFile.seek(lastLineOffset); } } catch(FileNotFoundException e) { Log.e("FileNotFoundException", "can't create FileOutputStream"); } catch (IOException e) { Log.e("IOException", "Failed to find last line"); } } else { try { newXmlFile.createNewFile(); } catch(IOException e) { Log.e("IOException", "exception in createNewFile() method"); } try { randomAccessFile = new RandomAccessFile(newXmlFile, "rw"); } catch(FileNotFoundException e) { Log.e("FileNotFoundException", "can't create FileOutputStream"); } } //we create a XmlSerializer in order to write xml data XmlSerializer serializer = Xml.newSerializer(); if (randomAccessFile == null) { return; } try { final StringWriter writer = new StringWriter(); serializer.setOutput(writer); if (!fileExists) { serializer.startDocument(null, true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(null, "root"); } else { serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); } serializer.startTag(null, "child1"); serializer.endTag(null, "child1"); serializer.startTag(null, "child2"); serializer.attribute(null, "attribute", "value"); serializer.endTag(null, "child2"); serializer.startTag(null, "child3"); serializer.text("some text inside child3"); serializer.endTag(null, "child3"); if (!fileExists) { serializer.endTag(null, "root"); } serializer.flush(); if (lastLine != null) { serializer.endDocument(); writer.append(lastLine); } // Add \n just for better output in console randomAccessFile.writeBytes(writer.toString() + "\n"); randomAccessFile.close(); Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e("Exception","error occurred while creating xml file"); e.printStackTrace(); } }
private void testXMLFiles(){ //在SD卡中创建一个名为“new.xml”的新文件 最终文件newXmlFile=新文件(Environment.getExternalStorageDirectory()+“/download/teste/audit.xml”); RandomAccessFile RandomAccessFile=null; final boolean fileExists=newXmlFile.exists(); 字符串lastLine=null; 如果(文件存在){ 试一试{ randomAccessFile=新的randomAccessFile(newXmlFile,“rw”); randomAccessFile.seek(0); if(null!=randomAccessFile){ 最终扫描仪=新扫描仪(newXmlFile); int lastLineOffset=0; int lastLineLength=0; while(scanner.hasNextLine()){ //+1表示结束线符号 lastLine=scanner.nextLine(); lastLineLength=lastLine.length()+2; lastLineOffset+=lastLineLength; } //不需要最后一行偏移 lastLineOffset-=lastLineLength; //我必须在最后一天之前完成 randomAccessFile.seek(lastLineOffset); } }catch(filenotfounde异常){ Log.e(“FileNotFoundException”,“无法创建FileOutputStream”); }捕获(IOE异常){ Log.e(“IOException”,“找不到最后一行”); } }否则{ 试一试{ newXmlFile.createNewFile(); }捕获(IOE异常){ e(“IOException”,“createNewFile()方法中的异常”); } 试一试{ randomAccessFile=新的randomAccessFile(newXmlFile,“rw”); }catch(filenotfounde异常){ Log.e(“FileNotFoundException”,“无法创建FileOutputStream”); } } //我们创建一个XmlSerializer来编写xml数据 XmlSerializer serializer=Xml.newSerializer(); if(randomAccessFile==null){ 返回; } 试一试{ 最终StringWriter编写器=新StringWriter(); serializer.setOutput(writer); 如果(!fileExists){ serializer.startDocument(null,true); serializer.setFeature(“http://xmlpull.org/v1/doc/features.html#indent-输出“,真实); serializer.startTag(null,“root”); }否则{ serializer.setFeature(“http://xmlpull.org/v1/doc/features.html#indent-输出“,真实); } serializer.startTag(null,“child1”); serializer.endTag(null,“child1”); serializer.startTag(null,“child2”); 属性(null,“attribute”,“value”); serializer.endTag(null,“child2”); serializer.startTag(null,“child3”); text(“child3中的某些文本”); endTag(null,“child3”); 如果(!fileExists){ serializer.endTag(null,“root”); } serializer.flush(); if(lastLine!=null){ serializer.endDocument(); writer.append(最后一行); } //添加\n只是为了在控制台中获得更好的输出 randomAccessFile.writeBytes(writer.toString()+“\n”); randomAccessFile.close(); Toast.makeText(getApplicationContext(),“Save!”,Toast.LENGTH\u SHORT.show(); }捕获(例外e){ Log.e(“异常”,“创建xml文件时出错”); e、 printStackTrace(); } }
child3中的一些文本
child3中的一些文本
- 存储初始xml中的所有标记(例如,使用您可以读取标记,同时写入新文件,并在末尾使用
应用新标记)李>XMLSerializer
“
@Wesley:你能帮我解决类似的问题吗?我也面临同样的问题。你有@D'yerMak'eru的解决方案吗?直到创建2º,json文件才正确生成。从3º开始,他在最后一个节点之后和结束节点根之前插入标记<代码>1º节点某些文本。。。2º3º向前一些文字…一些文字。。。有些…但是你给了我路。现在只需调整脚本以正确生成。谢谢,看来新的一行应该添加到新的一行中。@Sandstar:我有一个类似于上述问题的类似问题。你能帮我回答这个问题吗?我将不胜感激。@D'yerMak'er将检查它。谢谢@sandstar的回复。请调查一下。
<?xml version='1.0' standalone='yes' ?>
<root>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3>
<child1 />
<child2 attribute="value" />
<child3>some text inside child3</child3></root>