Java解析XML文件
发布时间:2020-05-24 16:04:27 所属栏目:Java 来源:互联网
导读:Java解析XML文件
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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 DomParse {
public DomParse(){
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
InputStream is=new FileInputStream("WebRoot/WEB-INF/hell.xml");
Document doc=dombuilder.parse(is);
Element root=doc.getDocumentElement();
NodeList books=root.getChildNodes();
if(books!=null){
for(int i=0;i<books.getLength();i++){
Node book=books.item(i);
if(book.getNodeType()==Node.ELEMENT_NODE){
String email=book.getAttributes().getNamedItem("email").getNodeValue();
System.out.println(email);
for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling()){
if(node.getNodeType()==Node.ELEMENT_NODE){
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);
}
}
}
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
new DomParse();
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
