java怎么在xml文件中保存和读取字符串数组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java怎么在xml文件中保存和读取字符串数组相关的知识,希望对你有一定的参考价值。
我使用jdom读写xml文件,想把一个字符串数组如:String week[] ="Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday";
保存到一个xml文件中,当需要时读出这个xml文件数据保存到一个字符串数组中该怎么处理?不用jdom用别的第三方jar也可以,请高手给一个例子,谢谢!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class XmlTest
public String[] xml2Array(String fileName) throws JDOMException, IOException
SAXBuilder b = new SAXBuilder();
Document xmlFile = b.build(new File(fileName));
Element root = xmlFile.getRootElement();
List ls = root.getChildren("week");
String weeks[]=new String[7];
for( int i = 0;i<ls.size();i++)
Element e = (Element)ls.get(i);
String week = e.getText();
weeks[i]=week;
return weeks;
public void array2Xml(String[] weekArray,String fileName) throws FileNotFoundException, IOException
Element weeks = new Element("weeks");
Document doc = new Document(weeks);
for(int i=0;i<weekArray.length;i++)
Element week = new Element("week");
week.setText(weekArray[i]);
weeks.addContent(week);
XMLOutputter out = new XMLOutputter();
out.setFormat(out.getFormat().setEncoding("GBK"));
out.output(doc,new FileOutputStream( new File(fileName)));
/**
* @param args
* @throws IOException
* @throws JDOMException
*/
public static void main(String[] args) throws JDOMException, IOException
XmlTest xml = new XmlTest();
String fileName = "week.xml";
String weeks[] ="Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday";
xml.array2Xml(weeks,fileName);
String testWeeks[] = xml.xml2Array(fileName);
for(String s:testWeeks)
System.out.println(s);
本回答被提问者采纳 参考技术B 你看看dom4j相关的解析方式
如何在 j2me 中创建保存和读取 XML 文件
【中文标题】如何在 j2me 中创建保存和读取 XML 文件【英文标题】:How to Create Save and Read Xml file in j2me 【发布时间】:2011-08-01 10:43:05 【问题描述】:我需要在 j2me 中创建 xml 文件并将这个文件保存到手机 并读取 xml 文件。
【问题讨论】:
【参考方案1】:查看此教程链接,了解 java/java-me 中的读/写概念是否相同
http://www.roseindia.net/xml/dom/CreatXMLFile.shtml
http://www.javazoom.net/services/newsletter/xmlgeneration.html
http://www.vogella.de/articles/JavaXML/article.html
【讨论】:
以上是关于java怎么在xml文件中保存和读取字符串数组的主要内容,如果未能解决你的问题,请参考以下文章