标签:
仅仅是为了总结与学习。
XML文件在我们的开发项目中经常使用,下面写了DOM解析的小例子。
DomTestFile.xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <MenuContainer> <menu order="1.0" menuname="测试1" description="描述1"> <menu order="1.1"> <value>测试1</value> </menu> </menu> <menu order="2.0" menuname="测试2" description="描述2"> <menu order="2.1"> <value>测试2</value> </menu> </menu> <menu order="3.0" menuname="测试3" description="描述3"> <menu order="3.1"> <value>测试3</value> </menu> </menu> </MenuContainer>
测试类如下:
1 package test.dom; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 import javax.xml.parsers.DocumentBuilder; 7 import javax.xml.parsers.DocumentBuilderFactory; 8 import javax.xml.parsers.ParserConfigurationException; 9 10 import org.w3c.dom.Document; 11 import org.w3c.dom.Element; 12 import org.w3c.dom.NodeList; 13 import org.xml.sax.SAXException; 14 15 public class DomTest { 16 17 /** 18 * Dom小例子:XML构建的菜单文件,解析 19 * @param args 20 * @throws ParserConfigurationException 21 * @throws IOException 22 * @throws SAXException 23 */ 24 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { 25 26 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 27 DocumentBuilder docb = dbf.newDocumentBuilder(); 28 InputStream is 29 = Thread.currentThread().getContextClassLoader().getResourceAsStream("DomTestFile.xml"); 30 //文档对象 31 Document doc = docb.parse(is); 32 //获取根节点 33 Element menuContainer = doc.getDocumentElement(); 34 //获取子节点 35 NodeList nl =menuContainer.getChildNodes(); 36 for(int i=0; i<nl.getLength(); i++) { 37 //过滤Text节点 38 if (nl.item(i).getNodeType() == Element.ELEMENT_NODE){ 39 Element e = (Element)nl.item(i); 40 //仅仅是展示 41 System.out.println("菜单顺序:" + e.getAttribute("order") + 42 ",菜单名称:" + e.getAttribute("menuname")); 43 } 44 45 } 46 } 47 48 }
演示效果如下:
标签:
原文地址:http://www.cnblogs.com/jayce-Hi/p/4199922.html