我想将一些内容写入
XML文件.为此我创建了一个
XML文件和带有元素,属性和值的写标签,其中包含以下数据:
XmlSerializer serializer = Xml.newSerializer(); serializer.startTag(null,element); serializer.attribute(null,atbname,value); serializer.text(text); serializer.endTag(null,tag);
解决方法
@H_404_11@ 看一下 this link.它应该让您了解如何向XML添加节点.这是一个片段.public DomXmlExample() { try { ///////////////////////////// //Creating an empty XML Document //We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); //////////////////////// //Creating the XML tree //create the root element and add it to the document Element root = doc.createElement("root"); doc.appendChild(root); //create a comment and put it in the root element Comment comment = doc.createComment("Just a thought"); root.appendChild(comment); //create child element,add an attribute,and add to root Element child = doc.createElement("child"); child.setAttribute("name","value"); root.appendChild(child); //add a text element to the child Text text = doc.createTextNode("Filler,... I could have had a foo!"); child.appendChild(text); ///////////////// //Output the XML //set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); trans.setOutputProperty(OutputKeys.INDENT,"yes"); //create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source,result); String xmlString = sw.toString(); //print xml System.out.println("Here's the xml:\n\n" + xmlString); } catch (Exception e) { System.out.println(e); } }