读取xml资料并转化为对象/对象转化为xml文件
读取xml文件并转化为对象/对象转化为xml文件
(引用xstream-1.4.1.jar)
agent.xml内容
<agent>
<calType>1</calType>
<helpList><help><a>1</a></help></helpList>
</agent>
public class Test {
private static XStream xstream = new XStream(new DomDriver());
static {
xstream.alias("agent", Agent.class);
xstream.alias("help", Help.class);
}
public static Agent prepareAgent() throws IOException {
String fileName = "doc/agent.xml";
StringBuilder sb = null;
InputStream input = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Agent agent = new Agent();
String a=sb.toString();
agent=(Agent) xstream.fromXML(a);
String b=xstream.toXML(agent);
System.out.println(agent.getHelpList().get(0).getA());
File f = new File("doc/result.xml");
FileWriter fw = new FileWriter(f);
BufferedWriter bfw = new BufferedWriter(fw);
bfw.write(b);
bfw.flush();
bfw.close();
return agent;
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO 自动生成方法存根
try {
prepareAgent();
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
(引用xstream-1.4.1.jar)
agent.xml内容
<agent>
<calType>1</calType>
<helpList><help><a>1</a></help></helpList>
</agent>
public class Test {
private static XStream xstream = new XStream(new DomDriver());
static {
xstream.alias("agent", Agent.class);
xstream.alias("help", Help.class);
}
public static Agent prepareAgent() throws IOException {
String fileName = "doc/agent.xml";
StringBuilder sb = null;
InputStream input = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Agent agent = new Agent();
String a=sb.toString();
agent=(Agent) xstream.fromXML(a);
String b=xstream.toXML(agent);
System.out.println(agent.getHelpList().get(0).getA());
File f = new File("doc/result.xml");
FileWriter fw = new FileWriter(f);
BufferedWriter bfw = new BufferedWriter(fw);
bfw.write(b);
bfw.flush();
bfw.close();
return agent;
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO 自动生成方法存根
try {
prepareAgent();
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}