หน้าเว็บ

วันศุกร์ที่ 14 ธันวาคม พ.ศ. 2555

java อ่าน XML file(Basic)

description.xml
<?xml version="1.0"?>
<description>
    <label>button</label>
    <title>button</title>
    <disabled>false</disabled>
    <hidden>false</hidden>
    <position>1</position>
    <icon>_icon/icon.png</icon>
    <role>public</role>
</description>
ReadXML.java

 
...
...
ServletContext servletContext = ...
String description = "/module/theme/description.xml";
try {
    InputStream moduleDesciptionXML = servletContext.getResourceAsStream(description);
    if (moduleDesciptionXML != null) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document document = dBuilder.parse(moduleDesciptionXML);
        document.getDocumentElement().normalize();

        LOG.debug("- root => {}", document.getDocumentElement().getNodeName());
        String label = getValueByTagName(document, "label");
        String title = getValueByTagName(document, "title");
        Boolean disabled = Boolean.valueOf(getValueByTagName(document, "disabled"));
        Boolean hidden = Boolean.valueOf(getValueByTagName(document, "hidden"));
        Integer position = Integer.valueOf(getValueByTagName(document, "position"));
        String role = getValueByTagName(document, "role");
        String icon = getValueByTagName(document, "icon");

        LOG.debug("  + label => {}", label);
        LOG.debug("  + title => {}", title);
        LOG.debug("  + disabled => {}", disabled);
        LOG.debug("  + hidden => {}", hidden);
        LOG.debug("  + position => {}", position);
        LOG.debug("  + role => {}", role);
        LOG.debug("  + icon => {}", icon);
    } else {
        LOG.debug("{} is null", description);
    }
} catch (Exception ex) {
    ex.printStackTrace();
}
...
...
...
private String getValueByTagName(Document document, String tag) {
    return document.getDocumentElement()
           .getElementsByTagName(tag)
           .item(0)
           .getChildNodes()
           .item(0)
           .getNodeValue();
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น