//导入的包
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;
//得到DOM解析器的工厂实例
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();//通过DOM工厂创建DOM解析器
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
//得到要解析的XML文档的输入流
InputStream is=new FileInputStream("bin/libracy.xml");
//解析XML文档的输入流
Document doc=dombuilder.parse(is);
//得到XML文档的节点
Element root=doc.getDocumentElement();
//得到节点的子节点
NodeList books=root.getChildNodes();
//循环输出
for(int i=0;i<books.getLength();i++)
{
//返回指定位置的Node对象
Node book=books.item(i);
String email=book.getAttributes().getNamedItem("email").getNodeValue();
System.out.println(email);
//遍历子节点
for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling())
{
if(node.getNodeName().equals("name")){
String name=node.getNodeValue();
String name1=node.getFirstChild().getNodeValue();
System.out.println(name);
System.out.println(name1);
}
if(node.getNodeName().equals("price")){
String price=node.getFirstChild().getNodeValue();
System.out.println(price);
}
}
}
//
本文介绍了一个使用 Java 进行 XML 文档解析的例子,包括如何读取 XML 文件、获取文档元素及其属性,并遍历节点等内容。
166

被折叠的 条评论
为什么被折叠?



