java使用dom和xpath读取xml

String filename = "conf/test.xml";
        
        DocumentBuilderFactory dbf = null;
        DocumentBuilder db = null;
        Document doc = null;
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression express = null;
        try
        {
            dbf = DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
            // 得到Document对象
            doc = db.parse(new File(filename));
            // 得到XPathExpression对象
            express = xpath.compile("//OS[@name='Linux']");
            // 根据XPathExpression对象查找对应的节点集合
            NodeList nodes = (NodeList) express.evaluate(doc, XPathConstants.NODESET);
            if (nodes != null)
            {
                // 遍历节点集合
                // 一般情况如果Xpath给定的能得到单个节点
                for(int i = 0 ;i < nodes.getLength(); i ++)
                {
                    Node node = nodes.item(i);
                    NamedNodeMap map = node.getAttributes();
                    // 打印节点的name属性值
                    System.out.println(map.getNamedItem("name").getNodeValue());
                }
            }
        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (SAXException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (XPathExpressionException e)
        {
            e.printStackTrace();
        }

 

你可能感兴趣的:(java,xml,linux,OS)