//创建book.xml 文件
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <name>微冷的雨</name> <price>100.0</price> </book> </books>
//解析代码
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 MyDom { public static void main(String[] args) throws Exception { readXml(); } private static void readXml() throws Exception { DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("src/book.xml"); NodeList list = document.getElementsByTagName("book"); for (int i = 0; i < list.getLength(); i++) { Element item = (Element)list.item(i); System.out.println(item.getElementsByTagName("name").item(0).getFirstChild().getNodeType()); } } }
时间: 2024-10-12 18:59:58