📄 listdom.java
字号:
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
public class ListDOM
{
//声明XML文件
static Document document;
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 设定解析的叁数
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
//导入XML文件
document = db.parse(new File("08_01.xml"));
// 获取根元素
Node root = document.getDocumentElement();
System.out.println("根元素: " + root.getNodeName());
NodeList nodes = root.getChildNodes();
// 获取所有的子节点
for (int i=0; i < nodes.getLength(); i++)
{
// 元素和文字节点
System.out.println("元素: " + nodes.item(i).getNodeName());
if (nodes.item(i).hasChildNodes())
{
NodeList childs = nodes.item(i).getChildNodes();
// 显示所有子节点
for (int j=0; j < childs.getLength(); j++)
{
int type1 = childs.item(j).getNodeType();
if (type1 == Node.ELEMENT_NODE)
{
System.out.print(" +-- " + childs.item(j).getNodeName());
System.out.println("/" + childs.item(j).getFirstChild().getNodeValue());
NodeList grandchilds = childs.item(j).getChildNodes();
for (int k=0; k < grandchilds.getLength(); k++)
{
int type2 = grandchilds.item(k).getNodeType();
if (type2 == Node.ELEMENT_NODE)
{
System.out.print(" +-- " + grandchilds.item(k).getNodeName());
System.out.println("/" + grandchilds.item(k).getFirstChild().getNodeValue());
}
}
}
}
}
}
// 显示指定元素的属性值
NodeList tagNodes = document.getElementsByTagName("book");
for (int i=0; i< tagNodes.getLength(); i++)
{
System.out.println("book(" + i + "):");
NamedNodeMap atts = tagNodes.item(i).getAttributes();
for (int j = 0; j < atts.getLength(); j++)
{
Node att = atts.item(j);
System.out.print(" +-- " + att.getNodeName());
System.out.println("/" + att.getNodeValue());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -