// 代码如下:主要问题是add方法中向Demo_03.xml文档中添加一doc封装的节点时报错:尝试在不允
//许的位置插入节点,查询过一些资料,但没弄明白,望大神指点,先谢谢啦
package xmlelementoperator;
import java.io.FileOutputStream; import java.io.IOException;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; 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.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException;
public class demo01 {
/** * 获得Document对象 * @param path 源文件路径 * @return Document对象 * @throws ParserConfigurationException * @throws SAXException * @throws IOException */
public static Document getDocument(String path) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbFactory.newDocumentBuilder();
Document doc = db.parse(path);
return doc;
}
@Test /* * 向xml文件中添加节点 */
public void add(){
try {
Document doc = getDocument("src/Demo_03.xml");
doc.createElement("云南人");
doc.setTextContent("云南人一般都热情");
//把创建的节点挂到根节点中
Element provience=(Element) doc.getElementsByTagName("中国").item(0); provience.appendChild(doc);
//上述操作只存在于内存中,要想保存到文件中还得借助transFormer对象才行
//写个方法吧
Transformer transformer=getTransFormer();
transformer.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("src/Demo_03.xml")));
} catch (ParserConfigurationException e) {
// TODO 自动生成的 catch 块 e.printStackTrace();
} catch (SAXException e)
{ // TODO 自动生成的 catch 块 e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块 e.printStackTrace();
}
catch (TransformerException e) {
// TODO 自动生成的 catch 块 e.printStackTrace(); }
}
public static Transformer getTransFormer(){
TransformerFactory tfFactory=TransformerFactory.newInstance();
Transformer transformer=null;
try { transformer = tfFactory.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO 自动生成的 catch 块 throw new TransformerFactoryConfigurationError(e);
}
return transformer;
}
}
你上w3cschool上看看吧,那个上面讲的挺详细的