Java XML Parse File parsePage(String filePath)

Here you can find the source of parsePage(String filePath)

Description

parse Page

License

Open Source License

Declaration

public static Map parsePage(String filePath) 

Method Source Code


//package com.java2s;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Map parsePage(String filePath) {
        File f = new File(filePath);
        Map map = new HashMap();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {/* www  .  jav  a 2  s. c om*/
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList pageList = doc.getElementsByTagName("page");
            for (int i = 0; i < pageList.getLength(); i++) {
                Node page = pageList.item(i);
                String id = page.getAttributes().getNamedItem("id").getTextContent();
                Map widgetMap = parseWidget(page.getChildNodes());
                map.put(id, widgetMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Map parseWidget(NodeList widgetList) {
        Map map = new HashMap();
        try {
            for (int i = 0; i < widgetList.getLength(); i++) {
                Node widget = widgetList.item(i);
                if (widget.getNodeName().equals("widget")) {
                    String id = widget.getAttributes().getNamedItem("id").getTextContent();
                    Map attrMap = parseAttribute(widget.getChildNodes());
                    map.put(id, attrMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Map parseAttribute(NodeList abtList) {
        Map map = new HashMap();
        try {
            for (int i = 0; i < abtList.getLength(); i++) {
                Node abt = abtList.item(i);
                if (abt.getNodeType() == 1) {
                    map.put(abt.getNodeName(), abt.getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

Related

  1. parseFile(File file)
  2. parseFile(File fn)
  3. parseFile(final File aFile)
  4. parseFile(String fileName)
  5. parseFile(String fname)
  6. parseXml(File file)
  7. parseXml(File file)
  8. parseXml(File file)
  9. parseXML(final File file)