java怎么在xml文件中保存和读取字符串数组

2024-11-13 06:42:10
推荐回答(2个)
回答1:

package test;

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

回答2:

你看看dom4j相关的解析方式