我有一个任务:
“任务是输出一个包含所有计算结果的XML文件。如果还提供了一个用于使用Web浏览器很好地查看生成的XML的XSL文件,那就太棒了。”
计算结果如下:
Feta Sushi;12.61;5.00;9.22;1.50;60.39;16.43;21.60;2.60;35.81;5.25.72
Siemak Beata;13.04;4.53;7.79;1.55;64.72;18.74;24.20;2.40;28.20;6.50.76
Hodson Wind;13.75;4.84;10.12;1.50;68.44;19.18;30.85;2.80;33.88;6.22.75
Seper Loop;13.43;4.35;8.64;1.50;66.06;19.05;24.89;2.20;33.48;6.51.01
我不知道如何将数据从Java应用程序输出到XML文件。还应该如何生成XSL文件?
如果有人抽出时间告诉我如何做到这一点会很棒。
答案 0 :(得分:0)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.rest.client;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author sxalam
*/
@XmlRootElement(name = "tasks")
public class Task {
String name;
List<Double> task;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Double> getTask() {
return task;
}
public void setTask(List<Double> task) {
this.task = task;
}
}
使用以下类从java对象生成XML
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBJavaToXml {
public static void main(String[] args) {
// creating country object
Task task = new Task();
task.setName("Feta Sushi");
List<Double> counter = new ArrayList<Double>();
counter.add(12.5);
counter.add(10.90);
task.setTask(counter);
try {
// create JAXB context and initializing Marshaller
JAXBContext jaxbContext = JAXBContext.newInstance(Task.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// for getting nice formatted output
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//specify the location and name of xml file to be created
File XMLfile = new File("C:\\task.xml");
// Writing to XML file
jaxbMarshaller.marshal(task, XMLfile);
// Writing to console
jaxbMarshaller.marshal(task, System.out);
} catch (JAXBException e) {
// some exception occured
e.printStackTrace();
}
}
}