File file = new File("data.xml"); SAXParserFactory.newInstance().newSAXParser().parse(file, new DefaultHandler(){ StringBuilder sb = new StringBuilder(); public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("item")){ sb = new StringBuilder(); } sb.append("<"); sb.append(qName); if(null != attributes){ for (int i = 0; i < attributes.getLength(); i++) { sb.append(" "); sb.append(attributes.getQName(i)); sb.append("="); sb.append("\""); sb.append(cdata(attributes.getValue(i)));//属性值特殊字符转换 sb.append("\""); } } sb.append(">"); } public void endElement (String uri, String localName, String qName) throws SAXException { sb.append("</" + qName + ">"); if(qName.equals("item")){ return; } //item节点结束,取得完整的节点xml使用dom方法解析 parseByDom(sb.toString()); } public void characters (char ch[], int start, int length) throws SAXException { //节点内容不转换特殊字符 String content = new String(ch, start, length); if(StringUtils.isNotBlank(content)){ sb.append("<![CDATA["); sb.append(content); sb.append("]]>"); } } /**通过DOM解析*/ public void parseByDom(String nodeXML){ //TODO:DocumentBuilderFactory.newInstance().newDocumentBuilder().parse } public String cdata(String text) { return text.replaceAll("&", "&") .replaceAll("'", "'").replaceAll("\"", """) .replaceAll(">", ">").replaceAll("<", "<"); } });