我正在嘗試編寫一個函數,用於存儲名稱和出生日期一個.xml文件。代碼應該看看.xml文件是否已經存在。當文件不存在時,會創建一個新的.xml文件並輸入數據。但是當第二次調用該函數時,追加時會出現一個雜散。請讓我知道如何解決這個問題。我是新來的java和XML解析,我今天剛剛開始。使用XML創建和追加交易功能是xmlCreator() 我粘貼下面附加xml文件時出現<xml version =「1.0」encoding =「UTF-8」standalone =「no」?>
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.FileWriter;
import java.nio.file.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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;
public class Exercise1 extends JPanel implements ActionListener{
String name;
String dateOfBirth;
//Labels to identify the fields
JLabel nameLabel;
JLabel dateOfBirthLabel;
//Strings for the labels
static String nameString = "Name";
static String dateOfBirthString = "Date Of Birth (dd/mm/yyyy)";
JTextField nameField;
JTextField dateOfBirthField;
JButton clearButton;
JButton saveAndProceedButton;
JButton bdayInNext5Days;
int serialNumber = 0;
FileWriter xmlFile;
public Exercise1()
{
super (new BorderLayout());
nameLabel = new JLabel(nameString);
dateOfBirthLabel = new JLabel(dateOfBirthString);
nameField = new JTextField();
nameField.setColumns(20);
nameLabel.setLabelFor(nameField);
dateOfBirthField = new JTextField();
dateOfBirthField.setColumns(20);
dateOfBirthLabel.setLabelFor(dateOfBirthField);
//Lay out the labels in a panel.
JPanel labelPane = new JPanel(new GridLayout(0,1));
labelPane.add(nameLabel);
labelPane.add(dateOfBirthLabel);
//Layout the text fields in a panel.
JPanel fieldPane = new JPanel(new GridLayout(0,1));
fieldPane.add(nameField);
fieldPane.add(dateOfBirthField);
clearButton = new JButton ("Clear");
clearButton.addActionListener (this);
saveAndProceedButton = new JButton ("Save and Proceed");
saveAndProceedButton.addActionListener (this);
serialNumber++;
bdayInNext5Days = new JButton("Bday in next 5 days");
bdayInNext5Days.addActionListener (this);
//Put the panels in this panel, labels on left,
//text fields on right.
add(labelPane, BorderLayout.LINE_START);
add(fieldPane, BorderLayout.CENTER);
add(clearButton, BorderLayout.LINE_END);
add(saveAndProceedButton, BorderLayout.SOUTH);
add(bdayInNext5Days, BorderLayout.NORTH);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Exercise 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add contents to the window.
frame.add(new Exercise1());
//Display the window.
frame.pack();
frame.setVisible(true);
}
private void xmlCreator(String name, String dateOfBirth) throws Exception{
Path path = Paths.get("Bday.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = null;
Element element = null;
Transformer transformer = null;
TransformerFactory transformerFactory = null;
if(Files.exists(path)) {
xmlFile = new FileWriter("Bday.xml",true);
document = documentBuilder.parse("Bday.xml");
element = document.getDocumentElement();
}
else{
xmlFile = new FileWriter("Bday.xml",true);
document = documentBuilder.newDocument();
element = document.createElement("Birthday");
document.appendChild(element);
}
Element Id = document.createElement("Id");
Id.appendChild(document.createTextNode(Integer.toString(serialNumber)));
element.appendChild(Id);
Element xmlName = document.createElement("Name");
xmlName.appendChild(document.createTextNode(name));
Id.appendChild(xmlName);
Element xmldateOfBirth = document.createElement("Date_Of_Birth");
xmldateOfBirth.appendChild(document.createTextNode(dateOfBirth));
Id.appendChild(xmldateOfBirth);
DOMSource source = new DOMSource(document);
transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult streamResult = new StreamResult(xmlFile);
transformer.transform(source, streamResult);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == clearButton){
nameField.setText("");
dateOfBirthField.setText("");
}
else if(source == saveAndProceedButton){
name = nameField.getText();
dateOfBirth = dateOfBirthField.getText();
try {
xmlCreator(name,dateOfBirth);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
nameField.setText("");
dateOfBirthField.setText("");
serialNumber++;
}
else{
}
}
public static void main (String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}}
輸出存儲在.xml文件的代碼如下
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Birthday>
<Id>1<Name>asdasd</Name>
<Date_Of_Birth>123</Date_Of_Birth>
</Id>
</Birthday>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Birthday>
<Id>1<Name>asdasd</Name>
<Date_Of_Birth>123</Date_Of_Birth>
</Id>
<Id>2<Name>adss</Name>
<Date_Of_Birth>12</Date_Of_Birth>
</Id>
你是什麼意思流浪的變化?額外的一行'<?xml version = ....'?即你是否得到了2個? – SomeDude
是的,我是。這是我的xml文件中的輸出。 <?XML版本= 「1.0」 編碼= 「UTF-8」 獨立= 「否」?> asdasd 123 DATE_OF_BIRTH> <?xml的版本= 「1.0」 編碼= 「UTF-8」 獨立= 「否」?> asdasd 123 DATE_OF_BIRTH> ADSS 12 DATE_OF_BIRTH> 的第一行來當我創建該文件,Bday.xml首次英寸第二個出現時,我打開相同的文件進行追加。 –