dom解析(二)
通过代码创建一个xml文件
package xml4; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; 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 com.sun.org.apache.bcel.internal.classfile.Field; public class domCreatexml { public static void main(String[] args) { // 创建工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 创建一个解析器 try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element rootElement = document.createElement("Students"); Element childElement = document.createElement("student"); childElement.setAttribute("id", "1"); rootElement.appendChild(childElement); Element namenode = document.createElement("name"); namenode.appendChild(document.createTextNode("黎明")); Element agenode = document.createElement("age"); agenode.appendChild(document.createTextNode("22")); Element sexnode = document.createElement("sex"); sexnode.appendChild(document.createTextNode("男")); childElement.appendChild(namenode); childElement.appendChild(agenode); childElement.appendChild(sexnode); document.appendChild(rootElement); try { // 获得转换器 Transformer transformer = TransformerFactory.newInstance().newTransformer(); // 设置换行 transformer.setOutputProperty(OutputKeys.INDENT, "ok"); try { //最关键 transformer.transform(new DOMSource(document), new StreamResult(new File("src/dadaming.xml"))); //transformer.transform(new DOMSource(document), new StreamResult()); } catch (TransformerException e) { e.printStackTrace(); } } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } } }