Horje
convert xml file to node tree with java Code Example
convert xml file to node tree with java
private static class TreeItemCreationContentHandler extends DefaultHandler {

    private TreeItem<String> item = new TreeItem<>();

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        // finish this node by going back to the parent
        this.item = this.item.getParent();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // start a new node and use it as the current item
        TreeItem<String> item = new TreeItem<>(qName);
        this.item.getChildren().add(item);
        this.item = item;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String s = String.valueOf(ch, start, length).trim();
        if (!s.isEmpty()) {
            // add text content as new child
            this.item.getChildren().add(new TreeItem<>(s));
        }
    }

}

public static TreeItem<String> readData(File file) throws SAXException, ParserConfigurationException, IOException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    XMLReader reader = parser.getXMLReader();
    TreeItemCreationContentHandler contentHandler = new TreeItemCreationContentHandler();

    // parse file using the content handler to create a TreeItem representation
    reader.setContentHandler(contentHandler);
    reader.parse(file.toURI().toString());

    // use first child as root (the TreeItem initially created does not contain data from the file)
    TreeItem<String> item = contentHandler.item.getChildren().get(0);
    contentHandler.item.getChildren().clear();
    return item;
}




Java

Related
what isz meaning of EL in jsp Code Example what isz meaning of EL in jsp Code Example
Type 'Response<any, Record<string, any>>' does not satisfy the constraint 'ServerResponse'. Types of property 'req' are incompatible. Code Example Type 'Response<any, Record<string, any>>' does not satisfy the constraint 'ServerResponse'. Types of property 'req' are incompatible. Code Example
convert javascript to java Code Example convert javascript to java Code Example
what does .set do in java Code Example what does .set do in java Code Example
java draw image Code Example java draw image Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
9