em đang học thao tác về file xml trong java đến đoạn ghi vào file xml thì nó format như sau:
</SinhVien><SinhVien><hoten>Trinh Ha</hoten><ngaysinh>10 - 11 - 1994</ngaysinh><gioitinh>0</gioitinh><lop>cntt_2013</lop></SinhVien>
em muốn hỏi làm sao để nó format xuống dòng , em cảm ơn .Dưới đây là file write:
package test3;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class writeXML {
public static void main(String[] args) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root;
String filePath = "C:\\Users\\user\\Documents\\BaiTapJava\\testProject\\src\\test2\\SinhVien.xml";
File xmlFile = new File(filePath);
try {
//neu file ton tai
if(xmlFile.isFile()) {
doc = docBuilder.parse(new FileInputStream(xmlFile));
doc.getDocumentElement().normalize();
root = doc.getDocumentElement();
}
else {
root = doc.createElement("sinhviens"); // create roo
doc.appendChild(root);
}
//create child
Element sinhvien = doc.createElement("SinhVien");
root.appendChild(sinhvien);
//ho ten
Element hoten = doc.createElement("hoten");
hoten.appendChild(doc.createTextNode("Ha Nam"));
sinhvien.appendChild(hoten);
Element ngaysinh = doc.createElement("ngaysinh");
ngaysinh.appendChild(doc.createTextNode("12 - 10 - 1994"));
sinhvien.appendChild(ngaysinh);
Element gioitinh = doc.createElement("gioitinh");
gioitinh.appendChild(doc.createTextNode("1"));
sinhvien.appendChild(gioitinh);
Element lop = doc.createElement("lop");
lop.appendChild(doc.createTextNode("cntt_2013"));
sinhvien.appendChild(lop);
//write the content into xml file
} catch (SAXException | IOException e) {
e.printStackTrace();
}
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult kq = new StreamResult(xmlFile);
trans.transform(source, kq);
System.out.println("File saved");
}
}
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?