什么是xml?
xml和html的区别?
在java中解析xml:
package org.xml.example; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Demo2 { public static void main(String [] args){ try { //创建文件工厂 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); //创建获取文件信息的对象 DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); //获取xml文件对象 Document document = builder.parse(new File("language.xml")); //获取根节点 Element root = document.getDocumentElement(); System.out.println("root="+root.getAttribute("cat")); //使用根节点根据子节点的名称获取子节点的集合 NodeList nodeList = root.getElementsByTagName("lan"); for(int i=0;i<nodeList.getLength();i++){ Element lan = (Element)nodeList.item(i); System.out.println("-------------------"); System.out.println("id="+lan.getAttribute("id")); //获取lan的子节点 NodeList childList = lan.getChildNodes(); for(int j=0;j<childList.getLength();j++){ Node node = childList.item(j); if(node instanceof Element){ System.out.println(node.getNodeName()+"="+node.getTextContent()); } } } } catch (Exception e) { e.printStackTrace(); } } }
<?xml vesion="1.0" encoding="UTF-8"?> <language cat="it"> <lan id="1"> <name>java</name> <ide>eclipse</ide> </lan> <lan id="2"> <name>c#</name> <ide>Visual studio</ide> </lan> <lan id="3"> <name>c</name> <ide>dep</ide> </lan> </language>
执行结果:
遇到的问题总结:
解决方法: