以下功能:
public static void initialize(){
try{
//creates new document
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element courseOne = doc.createElement("course");
doc.appendChild(courseOne);
Attr teacherOne = doc.createAttribute("Teacher");
teacherOne.setValue("Teacher A");
courseOne.setAttributeNode(teacherOne);
// write the data in an xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
transformer.transform(source, result);
}
catch(Exception e){
e.printStackTrace();
}
}
在指定文件中产生以下结果:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><course Teacher="Teacher A"/>
但是我试图将我的代码输出到文件中:
<course>
<Teacher> Teacher A </Teacher>
</course>
我可以更改什么才能使输出文件看起来像我想要的那样?
提前感谢您的帮助!