Java Tutorial/JSP/XML — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:07, 1 июня 2010

DOM Parser In JSP

Jsp code



<!--
Sams Teach Yourself JavaServer Pages in 21 Days (Paperback)
by Steven Holzner (Author), Steve Holzner (Author)
# Publisher: Sams; 1st edition (September 19, 2002)
# Language: English
# ISBN-10: 0672324490
# ISBN-13: 978-0672324499
-->
<%@ page import="javax.xml.parsers.*, org.xml.sax.*, org.xml.sax.helpers.*, org.w3c.dom.*, java.io.*"
 %>
<%!
public class xparser 
{
    String displayStrings[] = new String[1000];
    int numberDisplayLines = 0;
    public String[] displayDocument(String uri) 
    {
        try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } 
        catch (ParserConfigurationException pce) {}
        Document document = null;
        document = db.parse(uri);
        numberDisplayLines = 0;
        display(document, "");
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return displayStrings;
    } 
    public void display(Node node, String indent) 
    {
        if (node == null) {
            return;
        }
        int type = node.getNodeType();
        switch (type) {
            case Node.DOCUMENT_NODE: {
                displayStrings[numberDisplayLines] = indent;
                displayStrings[numberDisplayLines] += "&lt;?xml version=\"1.0\" encoding=\""+
                  "UTF-8" + "\"?&gt;";
                numberDisplayLines++;
                display(((Document)node).getDocumentElement(), "");
                break;
             }
             case Node.ELEMENT_NODE: {
                 displayStrings[numberDisplayLines] = indent;
                 displayStrings[numberDisplayLines] += "&lt;";
                 displayStrings[numberDisplayLines] += node.getNodeName();
                 int length = (node.getAttributes() != null) ? node.getAttributes().getLength() : 0;
                 Attr attributes[] = new Attr[length];
                 for (int i = 0; i < length; i++) {
                     attributes[i] = (Attr)node.getAttributes().item(i);
                 }
                 for (int i = 0; i < attributes.length; i++) {
                     Attr attribute = attributes[i];
                     displayStrings[numberDisplayLines] += " ";
                     displayStrings[numberDisplayLines] += attribute.getNodeName();
                     displayStrings[numberDisplayLines] += "=\"";
                     displayStrings[numberDisplayLines] += attribute.getNodeValue();
                     displayStrings[numberDisplayLines] += "\"";
                 }
                 displayStrings[numberDisplayLines] += "&gt;";
                 numberDisplayLines++;
                 NodeList childNodes = node.getChildNodes();
                 if (childNodes != null) {
                     length = childNodes.getLength();
                     indent += "&nbsp;&nbsp;&nbsp;&nbsp;";   
                     for (int i = 0; i < length; i++ ) {
                        display(childNodes.item(i), indent);
                     }
                 }
                 break;
             }
             case Node.CDATA_SECTION_NODE: {
                 displayStrings[numberDisplayLines] = indent;
                 displayStrings[numberDisplayLines] += "&lt;![CDATA[";
                 displayStrings[numberDisplayLines] += node.getNodeValue();
                 displayStrings[numberDisplayLines] += "]]&gt;";
                 numberDisplayLines++;
                 break;
             }
             case Node.TEXT_NODE: {
                 displayStrings[numberDisplayLines] = indent;
                 String newText = node.getNodeValue().trim();
                 if(newText.indexOf("\n") < 0 && newText.length() > 0) {
                     displayStrings[numberDisplayLines] += newText;
                     numberDisplayLines++;
                 }
                 break;
             }
             case Node.PROCESSING_INSTRUCTION_NODE: {
                 displayStrings[numberDisplayLines] = indent;
                 displayStrings[numberDisplayLines] += "&lt;?";
                 displayStrings[numberDisplayLines] += node.getNodeName();
                 String text = node.getNodeValue();
                 if (text != null && text.length() > 0) {
                     displayStrings[numberDisplayLines] += text;
                 }
                 displayStrings[numberDisplayLines] += "?&gt;";
                 numberDisplayLines++;
                 break;
            }    
        }
        if (type == Node.ELEMENT_NODE) {
            displayStrings[numberDisplayLines] = indent.substring(0, indent.length() - 24);
            displayStrings[numberDisplayLines] += "&lt;/";
            displayStrings[numberDisplayLines] += node.getNodeName();
            displayStrings[numberDisplayLines] += "&gt;";
            numberDisplayLines++;
            indent += "    ";
        }
    } 
}
%>
<HTML>
  <HEAD>
    <TITLE>Parsing an XML Document With DOM</TITLE>
  </HEAD>
  <BODY>
    <h1>Parsing an XML Document With DOM</h1>
    <% xparser p = new xparser(); 
        String[] s = p.displayDocument(application.getRealPath("/") + "test.xml");
 
        for(int i = 0; i < s.length; i++){
            if(s[i] != null){
    %>
            <%= s[i] %><BR>
    <%
            }
        }
    %>
    </BODY>
</HTML>





JSP SAX Parser

Jsp code



<!--
Sams Teach Yourself JavaServer Pages in 21 Days (Paperback)
by Steven Holzner (Author), Steve Holzner (Author)
# Publisher: Sams; 1st edition (September 19, 2002)
# Language: English
# ISBN-10: 0672324490
# ISBN-13: 978-0672324499
-->
<%@ page import="org.xml.sax.*, org.xml.sax.helpers.DefaultHandler, javax.xml.parsers.*, java.io.*" %>
<%!
javax.servlet.jsp.JspWriter localOut;
public class parser extends DefaultHandler
{
    String indent = "";
    void parse(String name) 
    {
        DefaultHandler handler = this;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new File(name), handler);
        } catch (Throwable t) {}
    }
    public void startDocument() throws SAXException
    {
        try{
            localOut.println("&lt;?xml version=\"1.0\" encoding=\""+"UTF-8" + "\"?&gt;<BR>");
        }
        catch(java.io.IOException e){}
    }
    public void endDocument() throws SAXException 
    {
    }
    public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attrs)
    throws SAXException 
    {
        try{
            String elementName = localName; 
            if ("".equals(elementName)) {
                elementName = qualifiedName; 
            }
            localOut.println(indent + "&lt;" + elementName);
            if (attrs != null) {
                for (int i = 0; i < attrs.getLength(); i++) {
                    String attributeName = attrs.getLocalName(i);  
                    if ("".equals(attributeName)) attributeName = attrs.getQName(i);
                    localOut.println(attributeName + "=");
                    localOut.println("\"" + attrs.getValue(i) + "\"");
                }
            }
            localOut.println("&gt;<BR>");
            indent += "&nbsp;&nbsp;&nbsp;&nbsp;";   
        }
        catch(java.io.IOException e){}
    }
    public void endElement(String namespaceURI, String localName, String qualifiedName)
    throws SAXException 
    {
        try{
            String elementName = localName; 
            if ("".equals(elementName)) {
                elementName = qualifiedName; 
            }
            indent = indent.substring(0, indent.length() - 24);
            localOut.println(indent + "&lt;/" + elementName + "&gt;");
            localOut.println("<BR>");
        }
        catch(java.io.IOException e){}
    }
    public void characters(char buf[], int offset, int len)
    throws SAXException
    {
        try{
            String s = new String(buf, offset, len);
            if (!s.trim().equals("")) {
                localOut.println(indent + "&nbsp;&nbsp;&nbsp;&nbsp;" + s);
                localOut.println("<BR>"); 
            }
        }
        catch(java.io.IOException e){}
    }
}        
%>
<HTML>
    <HEAD>
        <TITLE>Parsing an XML Document with SAX</TITLE>
    </HEAD>
    <BODY>
        <H1>Parsing an XML Document with SAX</H1>
    <%
        localOut = out;
        parser p = new parser();
        p.parse(application.getRealPath("/") + "test.xml");
    %>
    </BODY>
</HTML>