[java] xml파싱하기
private static void parseXml(String _url) throws Exception{
System.out.println("parse XML");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(_url);
doc.getDocumentElement().normalize();
NodeList itemNodeList = doc.getElementsByTagName("item");
System.out.println("count :" + itemNodeList.getLength());
for(int i =0; i < itemNodeList.getLength(); i++){
Node itemNode = itemNodeList.item(i);
if(itemNode.getNodeType() == Node.ELEMENT_NODE){
Element itemElement = (Element)itemNode;
NodeList titleNodeList = itemElement.getElementsByTagName("title");
Element titleElement = (Element)titleNodeList.item(0);
NodeList childTitleNodeList = titleElement.getChildNodes();
System.out.printf("[title : %s]\n", ((Node)childTitleNodeList.item(0)).getNodeValue());
NodeList linkNodeList = itemElement.getElementsByTagName("link");
Element linkElement = (Element) linkNodeList.item(0);
NodeList childLinkNodeList = linkElement.getChildNodes();
System.out.printf("[link : %s]\n", ((Node)childLinkNodeList.item(0)).getNodeValue());
NodeList pubDate = itemElement.getElementsByTagName("pubDate");
Element pubDateElement = (Element)pubDate.item(0);
NodeList childPubDateNodeList = pubDateElement.getChildNodes();
System.out.printf("[pub-date : %s]\n", ((Node)childPubDateNodeList.item(0)).getNodeValue());
}
}
}
System.out.println("parse XML");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(_url);
doc.getDocumentElement().normalize();
NodeList itemNodeList = doc.getElementsByTagName("item");
System.out.println("count :" + itemNodeList.getLength());
for(int i =0; i < itemNodeList.getLength(); i++){
Node itemNode = itemNodeList.item(i);
if(itemNode.getNodeType() == Node.ELEMENT_NODE){
Element itemElement = (Element)itemNode;
NodeList titleNodeList = itemElement.getElementsByTagName("title");
Element titleElement = (Element)titleNodeList.item(0);
NodeList childTitleNodeList = titleElement.getChildNodes();
System.out.printf("[title : %s]\n", ((Node)childTitleNodeList.item(0)).getNodeValue());
NodeList linkNodeList = itemElement.getElementsByTagName("link");
Element linkElement = (Element) linkNodeList.item(0);
NodeList childLinkNodeList = linkElement.getChildNodes();
System.out.printf("[link : %s]\n", ((Node)childLinkNodeList.item(0)).getNodeValue());
NodeList pubDate = itemElement.getElementsByTagName("pubDate");
Element pubDateElement = (Element)pubDate.item(0);
NodeList childPubDateNodeList = pubDateElement.getChildNodes();
System.out.printf("[pub-date : %s]\n", ((Node)childPubDateNodeList.item(0)).getNodeValue());
}
}
}
댓글
댓글 쓰기