본문 바로가기
백엔드기술/개발언어

Parser Demo

by RevFactory 2009. 12. 9.

package java_samples_hwang;
import org.w3c.dom.*;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
 *
 * @author hwang
 */
public class ParserDemo {
    public static void main(String args[])
    {
        try
        {     
        DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuildFactory.newDocumentBuilder();
        Document doc = docBuilder.parse("sample.xml");
        doc.getDocumentElement().normalize();
        String strnode = doc.getDocumentElement().getNodeName();
        System.out.println("root node name : "+strnode);
        NodeList nodeList = doc.getElementsByTagName("Language");
        System.out.println("no of nodes : "+nodeList.getLength());
        for(int i=0;i<nodeList.getLength();i++)
        {
            Node strNode = nodeList.item(i);
            if(strNode.getNodeType() == Node.ELEMENT_NODE)
            {
                Element nodeElement = (Element) strNode;
                NodeList nodeInnerList = nodeElement.getElementsByTagName("Name");
                Element nameElement = (Element)nodeInnerList.item(0);
                NodeList textFNList = nameElement.getChildNodes();
                System.out.println("Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());

                nodeInnerList = nodeElement.getElementsByTagName("Concepts");
                Element conceptElement = (Element)nodeInnerList.item(0);
                textFNList = conceptElement.getChildNodes();
                System.out.println("Concepts : "+((Node)textFNList.item(0)).getNodeValue().trim());
                textFNList.item(0).setTextContent("New Concepts");
               
            }
        }
        }
       /* catch (SAXParseException err)
        {
        System.out.println ("** Parsing error" + ", line "
             + err.getLineNumber () + ", uri " + err.getSystemId ());
        System.out.println(" " + err.getMessage ());

        }
        catch (SAXException e)
        {
        Exception x = e.getException ();
        ((x == null) ? e : x).printStackTrace ();

        }
        catch (Throwable t)
        {
        t.printStackTrace ();
        }
*/
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    }



 

'백엔드기술 > 개발언어' 카테고리의 다른 글

Swing Demo  (0) 2009.12.09
Override Demo  (0) 2009.12.09
Overload Demo  (0) 2009.12.09