xml中的代码
<?xml version="1.0" encoding="UTF-8"?> <books id="aaa"> <book id="1"> <name>书名1</name> <price>100</price> </book> <book id="2"> <name>书名2</name> <price>300</price> </book> </books>
java中的代码
import java.io.File; import java.io.IOException; import javax.lang.model.element.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.Node; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXml { public static void main(String[] args) { try { //java读取xml的方法。DOM方式 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse(new File("NewFile.xml")); //获取文档根元素 org.w3c.dom.Element root=document.getDocumentElement(); //输出根元素id的值 System.out.println(root.getAttribute("id")); //获取子级元素 NodeList list= root.getElementsByTagName("book"); //循环输出xml标签元素的值 for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Element book=(org.w3c.dom.Element)list.item(i); System.out.println("--------"); System.out.println("id="+book.getAttribute("id")); //获取所有子节点 NodeList list1=book.getChildNodes(); //循环输出子节点中的元素内容 for (int j = 0; j < list1.getLength(); j++) { org.w3c.dom.Node child=(org.w3c.dom.Node)list1.item(j); //去掉空白节点 if(child instanceof org.w3c.dom.Element){ System.out.println(child.getNodeName()+"标签内容是"+child.getTextContent()); } } //读取子节点中元素的值,都要重新创建一个element对象 /*org.w3c.dom.Element name=(org.w3c.dom.Element) book.getElementsByTagName("name").item(0); System.out.println("name="+name.getTextContent());*/ } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果
aaa -------- id=1 name标签内容是书名1 price标签内容是100 -------- id=2 name标签内容是书名2 price标签内容是300