在XML中增加节点 . 在原有的XML文件中,根据节点,添加数据

package testSort; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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; import org.w3c.dom.Text; /*** * * 在XML中增加节点 * 在原有的XML文件中,根据节点,添加数据 */ public class TestAddXMLNode { public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // 将给定文件的内容解析为一个 XML 文档,并且返回一个新的 DOM Document 对象。 Document doc = builder.parse("D://links.xml"); doc.normalize(); String name = "JAY"; String sex = "male"; String phone = "22324098"; //create an element named "link" Element link = doc.createElement("link"); //为姓名添加节点 Element linkName = doc.createElement("name"); Text textName = doc.createTextNode(name); //创建给定指定字符串的 Text 节点。 linkName.appendChild(textName); link.appendChild(linkName); //为性别添加节点 Element linkSex = doc.createElement("sex"); Text txtSex = doc.createTextNode(sex); linkSex.appendChild(txtSex); link.appendChild(linkSex); //为电话添加节点 Element linkPhone = doc.createElement("phone"); Text txtPhone = doc.createTextNode(phone); linkPhone.appendChild(txtPhone); link.appendChild(linkPhone); doc.getDocumentElement().appendChild(link);//return a root node of document TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new java.io.File( "D://links.xml")); transformer.transform(source, result); } catch (Exception e) { System.out.println("抛异常了"); } } }

<?xml version="1.0" encoding="UTF-8"?><links> <link> <name>Java!</name> <sex>male</sex> <phone>2232307</phone> </link> </links>

你可能感兴趣的:(在XML中增加节点 . 在原有的XML文件中,根据节点,添加数据)