用java解析这个xml文件

这个问题在这里已经有了答案:

  • 这是在Java中解析XML的最佳库[关闭] 7个答案

  • public static void main(String[] args) throws MarshalException,
    ValidationException, ParserConfigurationException, SAXException,
    IOException {
    
        File fXmlFile = new File(
                "/home/Parsing/src/com/parsing/test.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
    
        doc.getDocumentElement().normalize();
    
        Node node = doc.getDocumentElement().getParentNode();
    
        System.out.println(doc.getDocumentElement().getNodeName());
    
        NodeList itemList = node.getChildNodes();
        for (int i = 0; i < itemList.getLength(); i++) {
    
            Node nNode = itemList.item(i);
    
            System.out.println("Current Element : " + nNode.getNodeName());
    
            getChildNode(nNode.getChildNodes());
    
        }
    }
    
    private static void getChildNode(NodeList childNodes) {   // This method is going to retrieve the child nodes
        // TODO Auto-generated method stub
        System.out.println(childNodes.getLength());
    
        for (int i = 1; i < childNodes.getLength(); i++) {
            Node cNode = childNodes.item(i);
    
            System.out.println(cNode.getNodeName());
            /**
             * This will get the attribute of the node 
             */
            if (cNode.hasAttributes()) {
    
                NamedNodeMap nodeMap = cNode.getAttributes();
                for (int f = 0; f < nodeMap.getLength(); f++) {
                    System.out.println("Att " + nodeMap.item(f).getNodeName()
                            + " " + nodeMap.item(f).getNodeValue());
                }
            }
    
            if (cNode.hasChildNodes()) {
    
                // For getting the value if node has more than 2 or atleast two childs
    
                if (cNode.getChildNodes().getLength() >= 2) {
    
                    getChildNode(cNode.getChildNodes());
                }
    
                // For getting the node has no childs and it contains text node value
    
                else if (cNode.getNodeType() == cNode.ELEMENT_NODE) {
    
                    Element ele = (Element) cNode;
                    System.out.println("t" + ele.getTextContent());
    
                }
            }
    
            i++;
        }
    }
    

    一种方法是通过评估字符串手动执行。 另一种方法是使用所有可用的Java XML库之一... http://en.wikipedia.org/wiki/Java_API_for_XML_Processing


    答案是针对解析器类型的。 如果你打算使用DOM解析器,可能这会有所帮助。 这些是SAX解析器的例子。

    链接地址: http://www.djcxy.com/p/51711.html

    上一篇: parse this xml file in java

    下一篇: jaxb element with complexContent, restriction and attribute