public class TXML{ public static void main(String[] args) { try { File file = new File("d:/test.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodeList = doc.getElementsByTagName("dataset"); for (int i = 0; i < nodeList.getLength(); i++) { //System.out.println(doc.getElementsByTagName("bb_cargo_no").item(i).getFirstChild().getNodeValue()); //System.out.println(doc.getElementsByTagName("bb_operate_date").item(i).getFirstChild().getNodeValue()); } //这种方法比dom解析xml文件更高效;dom解析会把xml文件解析为一个树结构,如果大数据非常占用资源。 SAXReader reader = new SAXReader(); org.dom4j.Document xmlDoc=reader.read(file); Element root = xmlDoc.getRootElement(); Iterator ee = root.elementIterator(); while(ee.hasNext()) { Element ww = (Element) ee.next(); //System.out.println(ww.getName()+","+ww.getData()); }
} catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } TXML.writeDocument(TXML.getDocument(),"d:/a.xml"); }
public static org.dom4j.Document getDocument(){ org.dom4j.Document document = DocumentHelper.createDocument(); //生成一个接点 Element root = document.addElement("root"); //生成root的一个接点 Element category = root.addElement("category"); Element name = root.addElement("name"); //生产category的一个接点 Element id = category.addElement("id"); Element username = name.addElement("username"); //生成id里面的参数值 id.addAttribute("name","id"); username.addAttribute("name","username"); //生成id里面的值 id.addText("1"); username.addText("张三"); return document; }
public static void writeDocument(org.dom4j.Document document,String outFile){ try{ //读取文件 FileWriter fileWriter = new FileWriter(outFile); //设置文件编码 OutputFormat xmlFormat = new OutputFormat(); xmlFormat.setEncoding("UTF-8"); //创建写文件方法 XMLWriter xmlWriter = new XMLWriter(fileWriter,xmlFormat); //写入文件 xmlWriter.write(document); //关闭 xmlWriter.close(); }catch(IOException e){ System.out.println("文件没有找到"); e.printStackTrace(); } } }
http://shop107857222.taobao.com/ (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|