[java]代码库
1.主类
package s0210xml文件的读取和创建;
import java.io.File;
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) {
try {
//将xml文件转换为dom文件
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//目的是根据xml文件创建DOM文件
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("src/s0210xml文件的读取和创建/languages.xml"));//将传入的xml文件转换为document文件
//将xml文件转换为dom文件
Element root = document.getDocumentElement(); //获取当前文档的根元素
System.out.println("cat="+root.getAttribute("cat"));
NodeList list = root.getElementsByTagName("lan");//根据标签名获取所有元素,存入list中
//遍历子节点
for (int i = 0; i < list.getLength(); i++)
{
Element lan = (Element) list.item(i);
System.out.println("---------------");
System.out.println("id="+lan.getAttribute("id"));//element.getAttribute()方法获取element中的属性值
NodeList clist = lan.getChildNodes();//element.getChildNodes()方法获取所有的子节点
for (int j = 0; j < clist.getLength(); j++) //读取id下面的子节点数据
{
Node c = clist.item(j);
if (c instanceof Element) {
System.out.println(c.getNodeName()+"="+c.getTextContent());//element.getTextContent得到Node中属性的值
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.xml文件内容
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Languages cat="itt">
<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>