代码如下:
package com.accp.shi; import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; public class ReadXML { public static void main(String[] args){ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //文件夹制造工厂 DocumentBuilder bf = factory.newDocumentBuilder(); //用工厂制造出一个文件夹 Document doc = bf.parse("D://news.xml"); //使用DocumentBuilder类对象的parse()方法,来解析XML文件,并返回Document对象 NodeList channels = doc.getElementsByTagName("channel"); for(int i =0;i < channels.getLength(); i++){ Element channel = (Element)channels.item(i); Attr idAttr = doc.createAttribute("id"); idAttr.setValue("hello"); channel.setAttributeNode(idAttr); NodeList childs = channel.getChildNodes(); for(int j=0;j<childs.getLength();j++){ Node child = childs.item(j); if(child.getNodeName().equals("title")) System.out.println("<title>的频道标题:"+child.getFirstChild().getNodeValue()); if(child.getNodeName().equals("description")) System.out.println("<description>频道详细信息:"+child.getFirstChild().getNodeValue()); if(child.getNodeName().equals("item")){ NodeList items = child.getChildNodes(); for(int k=0;k<items.getLength();k++){ Node item = items.item(k); if(item.getNodeName().equals("title")) System.out.println("<title>的内容是新闻标题:"+item.getFirstChild().getNodeValue()); if(item.getNodeName().equals("link")) System.out.println("<link>的内容是新闻链接:"+item.getFirstChild().getNodeValue()); if(item.getNodeName().equals("description")) System.out.println("<item>/<description>的内容是新闻简介:"+item.getFirstChild().getNodeValue()); } } } } writeToXml(doc,"D://news2.xml"); } catch (Exception e) { e.printStackTrace(); } } /** * 将读出来的XML文件写到另一个XML文件中去 * 等于是新创建一个XML文件 * @param doc Document对象 * @param rptdesign 要存放的文件路径 */ private static void writeToXml(Document doc, String rptdesign) { try { OutputStream fileOutputStream = new FileOutputStream(rptdesign); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fileOutputStream); transformer.transform(source, result); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
以下是要被读取的XML文件
<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"> <channel> <title>新浪新闻</title> <description>新浪新闻频道</description> <item> <title>欧文里程碑进球直追三大传奇 </title> <link>http://sports.06383166011.shtml</link> <description>欧锦赛预选赛</description> </item> </channel> <channel> <title>QQ新闻</title> <description>QQ新闻频道</description> <item> <title>中国Q民已达到2.5亿</title> <link>http://www.qq.com</link> <description>网民新语</description> </item> <item> <title>北京申奥成功</title> <link>http://www.qq.com</link> <description>网民新语</description> </item> <item> <title>预祝北京奥运成功</title> <link>http://new.163.com</link> <description>网民新语</description> </item> </channel> </rss>