- XML文件设计为传输和存储数据,其焦点为数据内容。
- HTML设计为用来显示数据, 其焦点为数据外观。
- XML仅仅是文本文件,任何文本编辑器一般情况下都能对其进行编辑。
- XML没有预定义的标签,并且设定的标签是大小写敏感的。
标签还必须:
-
- 必须有根元素
- 属性值需要加引号
- 空格等会被保留
- 必须关闭标签
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(" <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(" <"+c.getNodeName()+">"+c.getTextContent()+"</"+c.getNodeName()+">");
}
}
System.out.println(" </lan>");
}
System.out.println("</language>");
} catch (ParserConfigurationException e) {
}
}
}
运行结果:
