慕粉3291149
2016-06-06 11:44
package test; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Book { NamedNodeMap attrs; NodeList childNodes; public NamedNodeMap getAttrs() { return attrs; } public void setAttrs(NamedNodeMap attrs) { this.attrs = attrs; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(childNodes.item(0).getNodeValue().split("")[1] + "<book "); for(int i=0;i<attrs.getLength();i++){ Node attr = attrs.item(i); sb.append(attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""); } sb.append(">"); for(int i=0;i<childNodes.getLength();i++){ Node child = childNodes.item(i); if(child.getNodeType()==Node.TEXT_NODE){ sb.append(child.getNodeValue()); } if(child.getNodeType()==Node.ELEMENT_NODE){ sb.append("<" + child.getNodeName() + ">"); sb.append(child.getFirstChild().getNodeValue()); sb.append("</" + child.getNodeName() + ">"); } } sb.append("</book>"); return sb.toString(); } public NodeList getChildNodes() { return childNodes; } public void setChildNodes(NodeList childNodes) { this.childNodes = childNodes; } } package test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class Homework { public static void main(String[] args) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse("books.xml"); NodeList booklist = document.getElementsByTagName("book"); List<Book> books = new ArrayList<Book>(); for(int i=0;i<booklist.getLength();i++){ Node book = booklist.item(i); NamedNodeMap attrs = book.getAttributes(); Book newBook = new Book(); newBook.setAttrs(attrs); NodeList childNodes = book.getChildNodes(); newBook.setChildNodes(childNodes); books.add(newBook); } System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); System.out.println("<bookstore>"); for(int i=0;i<books.size();i++){ System.out.println(books.get(i)); } System.out.println("</bookstore>"); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
请问你报的错是不是“找不到文件”?
如果是,你的xml文件复制到你当前的项目(project)下了吗
我把你的代码复制到我本地eclipse运行了 我的xml文件名为book.xml运行了一下没问题
Java眼中的XML---文件读取
83199 学习 · 431 问题
相似问题