将新元素附加到现有XML中

时间:2014-05-09 23:29:01

标签: java xml append

如果文档不存在但是当我尝试追加一个新的说法元素时,我得到了NullPointer异常,我没有得到任何错误。我只想在XML文档的末尾添加一个新元素。

java.lang.NullPointerException
at file.XMLWriter.writeXML(XMLWriter.java:34)
at gui.Main$1.actionPerformed(Main.java:49)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicRootPaneUI$Actions.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.KeyboardManager.fireBinding(Unknown Source)
at javax.swing.KeyboardManager.fireKeyboardAction(Unknown Source)
at javax.swing.JComponent.processKeyBindingsForAllComponents(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

GUI

package gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.BoxLayout;

import file.XMLWriter;
import Entity.Saying;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Main extends JFrame {

    private static final long serialVersionUID = -3565502930536078558L;
    private JButton commitButton;
    private JTextField sayingText;
    private JTextField categoryText;
    private JTextField authorText;
    private JPanel texts;
    private JPanel buttons;
    private XMLWriter writer;


    public Main(){
        setTitle("Sayings Creator");
        setSize(500, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE); 
        setVisible(true);
        getContentPane().setLayout(new BorderLayout());
        writer = new XMLWriter();


        texts = new JPanel();

        buttons = new JPanel(new FlowLayout());
        commitButton = new JButton("Commit");
        commitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                writer.writeXML(new Saying(sayingText.getText(), categoryText.getText(), authorText.getText()));

                sayingText.setText("Saying");
                categoryText.setText("Category");
                authorText.setText("Author");

            }
        });

        sayingText = new JTextField("Saying");
        sayingText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent arg0) {
                sayingText.setText("");
            }

        });
        sayingText.setToolTipText("Saying");

        categoryText = new JTextField("Category");
        categoryText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                categoryText.setText("");
            }
        });
        categoryText.setToolTipText("Category");


        authorText = new JTextField("Author");
        authorText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                authorText.setText("");
            }
        });
        authorText.setToolTipText("Author");

        getContentPane().add(texts, BorderLayout.CENTER);
        getContentPane().add(buttons, BorderLayout.SOUTH);
        texts.setLayout(new BoxLayout(texts, BoxLayout.Y_AXIS));


        texts.add(sayingText);

        texts.add(categoryText);

        texts.add(authorText);

        buttons.add(commitButton);


        getRootPane().setDefaultButton(commitButton);

        this.validate();
    }

}

XMLWriter的

package file;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import Entity.Saying;

public class XMLWriter {

    private String FILE_PATH = "sayings.xml"; 

    public void writeXML(Saying saying)
    {
        try 
        {
            File file = new File(FILE_PATH);
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            if(file.exists())
            {
                Node rootElement = doc.getFirstChild();

                Element sayingParent = doc.createElement("saying");
                rootElement.appendChild(sayingParent);

                Element firstname = doc.createElement("saying_text");
                firstname.appendChild(doc.createTextNode(saying.getSaying()));
                sayingParent.appendChild(firstname);

                Element lastname = doc.createElement("category");
                lastname.appendChild(doc.createTextNode(saying.getCategory()));
                sayingParent.appendChild(lastname);

                Element nickname = doc.createElement("author");
                nickname.appendChild(doc.createTextNode(saying.getAuthor()));
                sayingParent.appendChild(nickname);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(FILE_PATH));
                transformer.transform(source, result);
            }
            else
            {
                Element rootElement = doc.createElement("sayings");
                doc.appendChild(rootElement);

                Element sayingParent = doc.createElement("saying");
                rootElement.appendChild(sayingParent);

                Element firstname = doc.createElement("saying_text");
                firstname.appendChild(doc.createTextNode(saying.getSaying()));
                sayingParent.appendChild(firstname);

                Element lastname = doc.createElement("category");
                lastname.appendChild(doc.createTextNode(saying.getCategory()));
                sayingParent.appendChild(lastname);

                Element nickname = doc.createElement("author");
                nickname.appendChild(doc.createTextNode(saying.getAuthor()));
                sayingParent.appendChild(nickname);



                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(FILE_PATH));

                transformer.transform(source, result);
            }

        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }

}

2 个答案:

答案 0 :(得分:1)

无论文件是否已存在,您都在执行docBuilder.newDocument()初始化Document对象。

我建议你看看DocumentBuilder.parse

答案 1 :(得分:0)

当您的设备上存在文件时,

Document.parse正在运行。当您的设备上不存在该文件时,它无法正常工作,我们需要Document.newDocument

以下解决方案对我有用。

 try 
    {
        final File newXmlFile = new File(
                Environment.getExternalStorageDirectory() + "/audit.xml");

        String FILE_PATH = newXmlFile.getPath();

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

        if(newXmlFile.exists() == true)
        {
            docFactory.setValidating(false);

            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            Document doc = docBuilder.parse(newXmlFile);
            doc.getDocumentElement ().normalize ();


            Node rootElement = doc.getFirstChild();
            NodeList rootList = doc.getElementsByTagName("sayings");
            Node root = rootList.item(0);

            Log.i("ffffffffffffffffffffff", String.valueOf(rootElement));

            Element sayingParent = doc.createElement("saying");
            root.appendChild(sayingParent);

            Element firstname = doc.createElement("saying_text");
            firstname.appendChild(doc.createTextNode("Testss"));
            sayingParent.appendChild(firstname);

            Element lastname = doc.createElement("category");
            lastname.appendChild(doc.createTextNode("Tesedsfsdf"));
            sayingParent.appendChild(lastname);

            Element nickname = doc.createElement("author");
            nickname.appendChild(doc.createTextNode("ddddddd"));
            sayingParent.appendChild(nickname);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(FILE_PATH));
            transformer.transform(source, result);


        }
        else
        {
             DocumentBuilder newdocBuilder = docFactory.newDocumentBuilder();
             Document newdoc = newdocBuilder.newDocument();

            Element rootElement = newdoc.createElement("sayings");
            newdoc.appendChild(rootElement);

            Element sayingParent = newdoc.createElement("saying");
            rootElement.appendChild(sayingParent);

            Element firstname = newdoc.createElement("saying_text");
            firstname.appendChild(newdoc.createTextNode("sssssssssss"));
            sayingParent.appendChild(firstname);

            Element lastname = newdoc.createElement("category");
            lastname.appendChild(newdoc.createTextNode("sasaaaaaaaaa"));
            sayingParent.appendChild(lastname);

            Element nickname = newdoc.createElement("author");
            nickname.appendChild(newdoc.createTextNode("ccccccccccccc"));
            sayingParent.appendChild(nickname);


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(newdoc);
            StreamResult result = new StreamResult(new File(FILE_PATH));

            transformer.transform(source, result);


        }
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }