joi, 24 septembrie 2015

Java: XML Parser Sample

package test; 

import java.io.*; 

import javax.xml.parsers.*; 

import org.w3c.dom.Document; 
import org.w3c.dom.NodeList; 
import org.xml.sax.SAXException; 

public class TestXMLParser { 

    public static void main(String[] args) { 
        String xml = "<superflow name=\"BreakingPoint ClientSim HTTP Slow Post\" class=\"canned\">\r\n" 
                + "      <label>\r\n" 
                + "        <string>ClientSim HTTP Slow POST</string>\r\n" 
                + "      </label>\r\n" 
                + "      <description>\r\n" 
                + "        <string>This Super Flow enacts an HTTP POST DDoS attack by exploiting a web server's support for users with slow or intermittent connections. The Content-Length header contains a message body size that will be fulfilled over several TCP packets.[RFC 2616]</string>\r\n" 
                + "      </description>\r\n" 
                + "    </superflow>"
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
        InputStream is = new ByteArrayInputStream(xml.getBytes()); 
        try { 

            // Using factory get an instance of document builder 
            DocumentBuilder db = dbf.newDocumentBuilder(); 

            // parse using builder to get DOM representation of the XML file 
            Document dom = db.parse(is); 
            NodeList stringNodes = dom.getElementsByTagName("string"); 
            String superflowName = dom.getElementsByTagName("superflow").item(0).getAttributes().getNamedItem("name").getNodeValue().replace("\n"""), 
                   superflowLabel = stringNodes.item(0).getTextContent(), 
                   superflowDescription =stringNodes.item(1).getTextContent(); 
            System.out.println(superflowName); 
            System.out.println(superflowLabel); 
            System.out.println(superflowDescription); 
        } catch (ParserConfigurationException pce) { 
            pce.printStackTrace(); 
        } catch (SAXException se) { 
            se.printStackTrace(); 
        } catch (IOException ioe) { 
            ioe.printStackTrace(); 
        } 
    } 

Niciun comentariu:

Trimiteți un comentariu