import java.io.File;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;public class TestDom {...
java读取xml文件,结果写入新建的txt中。
读取xml文件用jdom.jar
写文件:看你是想原封不动的写到TXT中还是按照你想要得格式进行流写入到文本中。2013-05-03
import java.io.File;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;public class TestDom {public static void main(String[] args) {System.out.println(countMoney());}public static int countMoney(){int money=0;Set<Integer> set =new HashSet<Integer>();DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();DocumentBuilder db;try {db = dbf.newDocumentBuilder();Document doc=db.parse(new File("F:\\orders.xml"));Element root=doc.getDocumentElement();NodeList childs=root.getChildNodes();for(int i=0;i<childs.getLength();i++){if(childs.item(i).getNodeName().equals("order")){NodeList orderSons=childs.item(i).getChildNodes();for(int j=0;j<orderSons.getLength();j++){if(orderSons.item(j).getNodeName().equals("item")){NodeList itemSons=orderSons.item(j).getChildNodes();int n=0;int p=0;for(int k=0;k<itemSons.getLength();k++){if(itemSons.item(k).getNodeName().equals("qty")){n=Integer.parseInt(itemSons.item(k).getFirstChild().getNodeValue());}if(itemSons.item(k).getNodeName().equals("price")){p=Integer.parseInt(itemSons.item(k).getFirstChild().getNodeValue());}if(n*p!=0){money=n*p;set.add(money);}}}}}}}catch (Exception e) {e.printStackTrace();}if(set!=null){money=0;for(Iterator<Integer> it=set.iterator();it.hasNext();){money+=(int)it.next();}}return money;}} 以前做的练习,不过大同小异。别手懒了,动手试一试。 把上面的改改,得到你想要的内容,用流写入txt就行了。不会再问。
2013-05-03
使用sax或dom的方式进行读取,然后通过流的形式保存到指定txt文本内。2013-05-03