标签:
标签还必须:
JAVA读取XML文件
1,language.xml文件内容为:
<?xml version="1.0" encoding = "UTF-8" ?> <language cat = "it"> <lan id = "1"> <name>java</name> <IDE>Eclipse</IDE> </lan> <lan id = "2"> <name>Objective-C</name> <IDE>Xcode</IDE> </lan> <lan id = "3"> <name>C#</name> <IDE>Visual Studio</IDE> </lan> </language>
2,java代码
import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlRead { public static void main(String[] args) throws SAXException, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("language.xml")); Element root =document.getDocumentElement(); System.out.println("<language cat = \""+root.getAttribute("cat")+"\">"); NodeList list = root.getElementsByTagName("lan"); for(int i=0;i<list.getLength();i++){ Element lan = (Element) list.item(i); System.out.println("\t<lan id = \""+lan.getAttribute("id")+"\">"); NodeList clist = lan.getChildNodes(); for (int j = 0; j < clist.getLength(); j++) { Node c = clist.item(j); if (c instanceof Element) { System.out.println("\t\t<"+c.getNodeName()+">"+c.getTextContent()+"</"+c.getNodeName()+">"); } } System.out.println("\t</lan>"); } System.out.println("</language>"); } catch (ParserConfigurationException e) { } } }
运行结果:
标签:
原文地址:http://www.cnblogs.com/starainDou/p/4712318.html