Getting encoding type of a XML in java

前端 未结 3 1247
北恋
北恋 2021-01-12 04:26

I am parsing XML using DocumentBuilder in java 1.4.
XML has first line as

xml version=\"1.0\" encoding=\"GBK\"

I want to

3条回答
  •  执笔经年
    2021-01-12 04:46

    One way to this works like this

    final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( new FileReader( testFile ) );
    
    //running on MS Windows fileEncoding is "CP1251"
    String fileEncoding = xmlStreamReader.getEncoding(); 
    
    //the XML declares UTF-8 so encodingFromXMLDeclaration is "UTF-8"
    String encodingFromXMLDeclaration = xmlStreamReader.getCharacterEncodingScheme(); 
    

提交回复
热议问题