package XMLParser; /** * */ import java.io.File; import java.util.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.*; import javax.xml.parsers.*; import org.w3c.dom.Element; import org.w3c.dom.Node; //分析储存在文件中的xml文档 public class XMLParseWorker { /** * Variables * */ String XMLFileName=null; DocumentBuilderFactory factory=null; DocumentBuilder builder=null; Document document=null; Element element =null; NodeList list=null; Node node=null; int len=0; NodeList childList=null; Node childNode=null; String[] values=null; /** * * Methods * */ /** * Main Methods public static void main(String[] args) { String fileName="D://try//web.xml"; try{ XMLParseWorker worker=new XMLParseWorker(fileName); worker.printValuesByElementName("display-name"); worker.printValuesByElementName("description"); worker.printValuesByElementName("welcome-file-list"); worker.printValuesByElementName("welcome-file"); worker.printValuesByElementName("web-app"); // worker.printStruts(); } catch(Exception eee){ eee.printStackTrace(); } } * */ /** * XMLParseWorker(String XMLFileName) * */ public XMLParseWorker(String XMLFileName) { this.XMLFileName=XMLFileName; factory=DocumentBuilderFactory.newInstance(); try{ builder=factory.newDocumentBuilder(); document=builder.parse(XMLFileName); element =document.getDocumentElement(); element.normalize(); list=element.getChildNodes(); len=list.getLength(); } catch(Exception xpwe){ xpwe.printStackTrace(); } } /** * getValuesByElementName(String elementName) * */ public String[] getValuesByElementName(String elementName){ values=null; try{ list=document.getElementsByTagName(elementName); len=list.getLength(); values=new String[len]; for(int i=0;i<len;i++){ node=list.item(i); childList=node.getChildNodes(); childNode=childList.item(0); values[i]=childNode.getNodeValue(); } } catch(Exception e){ e.printStackTrace(); } return values; } /** * printValuesByElementName(String elementName) * */ public void printValuesByElementName(String elementName){ System.out.println(elementName+"="); System.out.println(Arrays.toString(getValuesByElementName(elementName))); } /** * Print * */ public void printStruts(){ list=document.getChildNodes(); element=document.getDocumentElement(); System.out.println("Root element =`"+element); printList(list); } public void printList(NodeList list){ for(int i=0;i<list.getLength();i++){ Node node=list.item(i); if(node.hasChildNodes()){ printList(node.getChildNodes()); } else{ System.out.println("Element =`"+node.getParentNode().getNodeName()+"`Value ={"+node.getNodeValue()); if((node.getNodeValue().trim()).length()>1){ System.out.println("}"); } } } } }