使用DOM创建xml文件
创建xml的代码如下:
public class CreateXML { public static void main(String[] args) { DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder=factory.newDocumentBuilder(); Document documnet= builder.newDocument(); Element root=documnet.createElement("languages"); root.setAttribute("cat", "it"); Element lan1=documnet.createElement("lan"); lan1.setAttribute("id", "1"); Element name1=documnet.createElement("name"); name1.setTextContent("java"); Element ide1=documnet.createElement("ide"); ide1.setTextContent("eclipse"); lan1.appendChild(name1); lan1.appendChild(ide1); Element lan2=documnet.createElement("lan"); lan2.setAttribute("id", "2"); Element name2=documnet.createElement("name"); name2.setTextContent("c#"); Element ide2=documnet.createElement("ide"); ide2.setTextContent("visual studio"); lan2.appendChild(name2); lan2.appendChild(ide2); Element lan3=documnet.createElement("lan"); lan3.setAttribute("id", "3"); Element name3=documnet.createElement("name"); name3.setTextContent("swift"); Element ide3=documnet.createElement("ide"); ide3.setTextContent("visual studio"); lan3.appendChild(name3); lan3.appendChild(ide3); root.appendChild(lan1); root.appendChild(lan2); root.appendChild(lan3); documnet.appendChild(root); //使用transformer将xml文档转换成其他格式 TransformerFactory tfactory=TransformerFactory.newInstance(); Transformer former=tfactory.newTransformer(); //将xml内容以字符串输出 StringWriter writer=new StringWriter(); former.transform(new DOMSource(documnet), new StreamResult(writer)); System.out.println(writer.toString()); //将xml内容保存为文件 former.transform(new DOMSource(documnet), new StreamResult(new File("newxml.xml")));
} catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
将xml的内容放入document对象后,直接把这document用toString输出会是null
此时需要进行使用Transformer进行转换,如果想变成字符串输出可以借助stringwriter,如果想变成文件保存直接用file
备注:eclipse中可以用ctrl+i进行格式化xml文件,更易于观察