Uknown XML file into pojo

前端 未结 1 2027
抹茶落季
抹茶落季 2021-01-16 15:18

Is there any way to take an unknown schema xml file and convert the values, tags, etc from the xml file into pojo? I looked at jaxb and it seems like the best way to use tha

相关标签:
1条回答
  • 2021-01-16 16:17

    In the hope that this helps you to understand your situation!

    public static void dumpAllNodes( String path ) throws Exception {
        DocumentBuilder parser = 
          DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = parser.parse(new File(path));
        NodeList nodes = doc.getElementsByTagNameNS( "*", "*" );
        for( int i = 0; i < nodes.getLength(); i++ ){
            Node node = nodes.item( i );
            System.out.println( node.getNodeType() + " " + node.getNodeName() );
        }
    }
    

    The NodeList nodes contains all element nodes, in document order (opening tag). Thus, elements contained within elements will be in that list, all alike. To obtain the attributes of a node, call

    NamedNodeMap map = node.getAttributes();
    

    The text content of a node is available by

    String text = node.getTextContent();
    

    but be aware that calling this returns the text in all elements of a subtree.

    OTOH, you may call

    Element root = doc.getDocumentElement();
    

    to obtain the root element and then descend the tree recursively by calling Element.getChildNodes() and process the nodes (Element, Attr, Text,...) one by one. Also, note that Node.getParentNode() returns the parent node, so you could construct the XPath for each node even from the flat list by repeating this call to the root.

    It simply depends what you expect from the resulting data structure (what you call ArrayList). If, for instance, you create a generic element type (MyElement) containing one map for attributes and another one for child elements, the second map would have to be

    Map<String,List<MyElement>> name2elements
    

    to provide for repeated elements - which makes access to elements occurring only once a little awkward.

    I hope that I have illustrated the problems of generic XML parsing, which is not a task where JAXB can help you.

    0 讨论(0)
提交回复
热议问题