正则表达式处理XML文件 高手们看一下吧!
本人想从一XML文件中读取出来,然后用正则表达式判断一下该文件是否是XML文件,自己尝试编了一个小程序,可是遇到了一些逻辑上的错误:越看越迷,请高手们指点一下吧!!
本人要读取的XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<student>
<id>01</id>
</student>
本人编写的代码如下:
package wang.regex.file;
import java.io.*;
import java.util.regex.*;
public class RegexFile
{
public static void main(String[] args)
{
// TODO 自动生成方法存根
try
{
File f = new File("D:\\王山虎\\资料\\正则表达式解析xml\\lianxi01.xml");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
System.out.println(line);
Pattern p = Pattern
.compile("<\\?xml\\sversion=\"1.0\"\\sencoding=\"UTF-8\"\\?>");
Matcher m = p.matcher(line);
boolean b = m.matches();
System.out.println("加上读取文件时的匹配了:" + b);
if (ceshiOther(br))
{
System.out.println("匹配成功!!");
}
} catch (FileNotFoundException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
System.out.println("没有发现该文件!!");
} catch (IOException e)
{
// TODO 自动生成 catch 块
System.out.println("读取文件失败!!");
e.printStackTrace();
}
}
public static boolean ceshiOther(BufferedReader br)
{
String line = null;
Pattern p1 = Pattern.compile("\\s*<\\w{1,}>");
Pattern p2 = Pattern.compile("\\s*<\\w{1,}.*</\\w{1,}>");
Pattern p3 = Pattern.compile("\\s*</\\w{1,}>");
boolean flag1 = false;
boolean flag2 = false;
int i = 1;
try
{
while ((line = br.readLine()) != null)
{
System.out.println(line + " " + i);
Matcher m1 = p1.matcher(line);
if (m1.matches() == false)
{
Matcher m2 = p2.matcher(line);
flag2 = m2.find();
System.out.println(m2.find());
// continue;
} else if (flag2 == false && (m1.find() == false))
{
System.out.println("程序执行到这了啊!!");
Matcher m3 = p3.matcher(line);
// System.out.println(m3.matches());
}
i++;
}
if (flag2)
{
flag1 = true;
}
} catch (IOException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
System.out.println("读取其它文件时失败了!!");
}
return flag1;
}
}