DOMSource对于String to XML仍然是空的

时间:2015-09-09 01:20:19

标签: java xml domparser

我正在尝试使用DOMParser从String生成XML文件。代码段如下:

public class SomeClassToSendString () 
{

    private XMLBuilder xmlBuilder;

    public SomeClassToSendString(String fileName) {
        this.fileName = fileName;
        xmlBuilder = new XMLBuilder(fileName)
    }

    public void writeHeader{
        xmlBuilder.writeRootElements(); }
    public void writeRecords(String record){
       xmlBuilder.writeRecords(record); }
    public void close{
        xmlBuilder.close() }
}

public class XMLBuilder {
    private String fileName;
    private DocumentBuilderFactory docFactory;
    private DocumentBuilder docBuilder;
    private Document document;
    private Element rootElement;
    private Element childOfRoot;

    public XMLFileHandler(String fileName) throws ParserConfigurationException {

        this.fileName = fileName;
        docFactory = DocumentBuilderFactory.newInstance();
        docBuilder = docFactory.newDocumentBuilder();
        document = docBuilder.newDocument();
    }

    public void writeRootElements() throws AppException{

        try {
            // root element
            rootElement = document.createElement("root");
            document.appendChild(rootElement);

            // child element
            childOfRoot = document.createElement("childOfRoot");
            rootElement.appendChild(childOfRoot);
        } catch (Exception e) {
            logger.error(e);
        }
    }
    public void writeRecords(String string) {
        Element childOfFirstChild = document.createElement("childOfFirstChild");
        childOfRoot.appendChild(childOfFirstChild);
                Element record = document.createElement("record");
        record.appendChild(document.createTextNode(string));
        childOfFirstChild.appendChild(record); }

    public void close() {
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult xmlResultFile = new StreamResult(new File(fileName));

        transformer.transform(source, xmlResultFile); }
}

Document仍为null,因此DOMSource为空。我无法弄清楚我的偏离轨道。 感谢。

0 个答案:

没有答案