zoukankan      html  css  js  c++  java
  • 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 DocDemo {
        private Document document = null;
        public void getDocument() {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder builder = factory.newDocumentBuilder();
                document = builder.parse("收藏信息.xml");
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        
        public void show() {
            //找到所有的Brand
            NodeList nodeList = document.getElementsByTagName("Brand");
            //遍历每一个Brand
            for(int i = 0;i<nodeList.getLength();i++) {
                Node node = nodeList.item(i);
                //转成元素类型
                Element eleBrand = (Element)node;
                System.out.println("品牌"+eleBrand.getAttribute("name"));
                //找到当前Brand的所有子节点
                NodeList typeList = eleBrand.getChildNodes();
                //遍历每一个子节点
                for(int j = 0;j<typeList.getLength();j++) {
                    Node typeNode = typeList.item(j);
                    //因为Brand的子节点中可能有非元素点,比如属性节点、文本节点
                    //所以要先判断该子节点是否是一个元素节点,如果是才能进行强转
                    //typeNode.getNodeType()这个方法时获取当前节点的字节类型————元素节点、属性节点、文本节点
                    if(typeNode.getNodeType() == Node.ELEMENT_NODE) {
                        //转换成元素对象
                        Element eleType = (Element)typeNode;
                        System.out.println("	型号:"+eleType.getAttribute("name"));
                    }
                    
                }
            }
        }
        public static void main(String[] args) {
            DocDemo d = new DocDemo();
            d.getDocument();
            d.show();
        }
    }

  • 相关阅读:
    mybatis返回map类型数据空值字段不显示(三种解决方法)
    linux各种资源查看
    ssh代理
    python 自定义ping编写
    python 备忘(协程,多进程)
    python 控制电源模块for循环写法
    XPath 语法
    python 自定义去掉特殊字符串
    ssh证书登陆vpc/并且反向代理
    cmder设置
  • 原文地址:https://www.cnblogs.com/zxbaoer/p/10513715.html
Copyright © 2011-2022 走看看