效果如图:
JAVA 代码
public static void main(String[] args) throws Exception { String str = "<row PTID="80268175" ZYH="2002868" XM="刘云1" YZLB="0" YSXM="王丽" ZYCH="11B40" CZLX="QR" CXSJ="2019-12-12 13:51:17"/> " + "<row PTID="80268176" ZYH="2002868" XM="刘云2" YZLB="0" YSXM="王丽" ZYCH="11B41" CZLX="TY" CXSJ="2019-12-12 13:51:17"/> " + "<row PTID="80268176" ZYH="2002868" XM="赵云1" YZLB="0" YSXM="王丽" ZYCH="11B42" CZLX="TY" CXSJ="2019-12-12 13:51:17"/> " + "<row PTID="80268176" ZYH="2002868" XM="刘云3" YZLB="0" YSXM="王丽" ZYCH="11B43" CZLX="QR" CXSJ="2019-12-12 13:51:17"/>"; System.out.println("XML => " + str + " "); Search("11B40", str); Search("刘云", str); } /** * 打印查询结果 * @param keyWords * @param str */ private static void Search(String keyWords, String str) { System.out.println("查询关键字 => " + keyWords); Pattern pRow = Pattern.compile(".*" + keyWords + ".*"); Matcher mRow = pRow.matcher(str); String result = ""; while (mRow.find()) { String rowStr = mRow.group(0); if (StringUtil.isNotEmpty(rowStr)) { //方便阅读,瓶贴ID 的获取,不使用公用方法 Pattern pPTID = Pattern.compile(" PTID="(.+?)""); Matcher mPTID = pPTID.matcher(rowStr); while (mPTID.find()) { result += "瓶贴ID:" + mPTID.group(1) + " "; } //将上面瓶贴ID抽成方法 result += "姓名:" + getFieldValue(rowStr, "XM"); result += "床号:" + getFieldValue(rowStr, "ZYCH"); if (rowStr.contains("CZLX="QR"")) { result += "状态:取药 "; } if (rowStr.contains("CZLX="CX"")) { result += "状态:撤销 "; } if (rowStr.contains("CZLX="TY"")) { result += "状态:退药 "; } if (rowStr.contains("CZLX="CXTY"")) { result += "状态:撤销退药 "; } result += " " + getFieldValue(rowStr, "CXSJ"); } result += " "; } System.out.println(result); } /** * 获取字段值 * @param rowStr * @param field * @return */ private static String getFieldValue(String rowStr, String field) { String result = ""; Pattern pXM = Pattern.compile(" " + field + "="(.+?)""); Matcher mXM = pXM.matcher(rowStr); while (mXM.find()) { result += mXM.group(1) + " "; } return result; }