XML文件没有正确写入?

时间:2014-05-26 15:51:18

标签: xml dom format

以下功能:

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>

我可以更改什么才能使输出文件看起来像我想要的那样?

提前感谢您的帮助!

0 个答案:

没有答案