<?xml version="1.0" encoding="GB2312" standalone="no"?>比如上面这个xml文件编码为gb2312,我将其通过string转换成新的utf-8编码xml文。现在需要替换表头声明的GB2312为UTF-8,<?xml version="1.0" encoding="UTF-8" standalone="no"?> ,求一个正则表达式。

解决方案 »

  1.   

    字符串替换就行,表达式就是encoding="GB2312"
      

  2.   

    不行的,很多比如gib5什么的编码,我全部转utf8
      

  3.   

    public static String findEncoding(File f)throws Exception{
    BufferedReader reader=null;
    String line=" ";
    String encoding=" ";
    try{
    reader=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
    do{
    line=reader.readLine();

    }while(line!=null&&!line.startsWith("<?xml"));
    }catch(Exception e){
    e.printStackTrace();
    try{
    reader.close();
    }catch(Exception ee){
    ee.printStackTrace();
    }
    }
    if(line==null)
    line=" ";
    Pattern pattern=Pattern.compile("encoding\\s*=\\s*\"(\\w+[-,_]?){1,}\"");
        Matcher matcher = pattern.matcher(line.toLowerCase());
        if(matcher.find()){
         encoding=matcher.group();
       
        }
       
      Pattern last=Pattern.compile("\"(\\w+[-,_]?){1,}\"");
      Matcher m=last.matcher(result);
      if(m.find()){
       
       return result.substring(m.start()+1,m.end()-1);
      }
      else{

      return " ";
      }
    }xml标准要求声明必须是第一行