XML解析
Posted 孤独的菜鸟----
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML解析相关的知识,希望对你有一定的参考价值。
1.XML文件
<?xml version="1.0" encoding="UTF-8"?>
<Languages cat="it">
<lan id="1">
<name>Java</name>
<ide>Eclipse</ide>
</lan>
<lan id="2">
<name>Swift</name>
<ide>Xcode</ide>
</lan>
<lan id="3">
<name>C#</name>
<ide>Visual Studio</ide>
</lan>
</Languages>
2.JAVA类
package cn.edu.qust.xml;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 ReadXML
public static void main(String[] args)
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
builder = builderFactory.newDocumentBuilder();
// 读取文档,注意文件路径
Document document = builder.parse("./src/languages.xml");
// 获取根节点
Element element = document.getDocumentElement();
// 获取节点标签名,属性值
System.out.println(element.getTagName() + " cat " + element.getAttribute("cat"));
NodeList list = element.getElementsByTagName("lan");
for (int i = 0; i < list.getLength(); i++)
System.out.println("==============");
// 进行类型转换,否则报类型装换异常
Element lanNode = (Element) list.item(i);
System.out.println("id = " + lanNode.getAttribute("id"));
NodeList chlidList = lanNode.getChildNodes();
for (int j = 0; j < chlidList.getLength(); j++)
Node child = chlidList.item(j);
if (child instanceof Element)
System.out.println(child.getNodeName() + " = " + child.getTextContent());
catch (ParserConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
3.打印日志
Languages cat it
==============
id = 1
name = Java
ide = Eclipse
==============
id = 2
name = Swift
ide = Xcode
==============
id = 3
name = C#
ide = Visual Studio
以上是关于XML解析的主要内容,如果未能解决你的问题,请参考以下文章