我编写了一个程序来解析XML文件,以获取一个名为SerialNum的特定标记值,该值包含在Header标记中.该文件构造如下:
它包含1个标题和1个正文
Header可能包含许多SerialNum标记.我们需要提取最后一个标签的值.
我使用Stax解析器来获取SerialNum值,我编写了这段代码:
public String findIdValue(HttpServletRequest request) { String serialNumberValue = null; if(request != null){ ServletInputStream servletInstream; try { servletInstream = request.getInputStream(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader xmlStreamReader = factory.createXMLStreamReader(servletInstream); //begin parsing if we get//end parsing if we get int event = xmlStreamReader.getEventType(); boolean enableToParse = false; boolean gotSerialNumber = false; boolean parseComplete = false; while( (xmlStreamReader.hasNext()) && (!parseComplete) ){ switch(event) { case XMLStreamConstants.START_ELEMENT: if("Header".equals(xmlStreamReader.getLocalName())){ //tag is header, so begin parse enableToParse = true; }else if(("SerialNum".equals(xmlStreamReader.getLocalName())) && (enableToParse) ){ //tag is serialNum so enable to save the value of serial number gotSerialNumber = true; } break; case XMLStreamConstants.CHARACTERS: //get serial number and end the parsing if(gotSerialNumber){ //get wsa and end the parsing serialNumberValue = xmlStreamReader.getText(); gotSerialNumber = false; } break; case XMLStreamConstants.END_ELEMENT: //when we get end the parse //when we get reinit flags //when we get end the parse even we don't get a serial number if("Header".equals(xmlStreamReader.getLocalName())){ parseComplete= true; }else if("SerialNum".equals(xmlStreamReader.getLocalName())){ //reinit flag when we get tag gotSerialNumber = false; } break; default: break; } event = xmlStreamReader.next(); } } catch (final XMLStreamException e) { //catch block LOG.info("Got an XMLStreamException exception. " + e.getMessage()); } catch (final IOException e1) { //catch block LOG.info("Got an IOException exception. " + e1.getMessage()); } } return serialNumberValue; }or
此代码提取所需的值但代码质量不是很好:它不易于阅读和维护.它包含一个switch case和if else块嵌套在while循环中.使用哪种设计模式来提高代码质量?