dom4j如何生成、解析xml文件
展开全部
import java.io.Reader;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;1.dom4j生成xmlDocument doc = DocumentHelper.createDocument();doc.setXMLEncoding("UTF-8");Element root = doc.addElement("ROOT");Element body = root.addElement("BODY");body.addAttribute("name", "张三");body.addText("一个人");//生成String字符串String xml = doc.asXMl();InputStream input = new ByteArrayInputStream(xml.getBytes("UTF-8"));//写到磁盘OutputFormat format = OutputFormat.createPrettyPrint();format.setEncoding("UTF-8");//fiename为文件名称XMLWriter writer = new XMLWriter(new FileOutputStream(new File(filename)),format);writer.write(doc);writer.close();//写入流中ByteArrayOutputStream tOut = new ByteArrayOutputStream();OutputFormat outFormat = OutputFormat.createCompactFormat();outFormat.setEncoding("UTF-8");XMLWriter output = new XMLWriter(tOut, outFormat);output.write(document);output.close();new ByteArrayInputStream(tOut.toByteArray())2.dom4j解析xml//Reader reader = new InputStreamReader(in, "utf-8");//SAXReader sr = new SAXReader();//Document doc = sr.read(reader);SAXReader sr = new SAXReader();Document doc = sr.read(InputStream);Element root = doc.getRootElement();List lists = root.Elements("BODY");Element body = root.element("BODY");body.attributeValue("name")root.elementText("BODY");//修改节点属性值和文本值body.attribute("name").setValue("李四");body.setText("这不是一个人");root.remove(body);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询