public static List parse(BufferedReader br, String dataUnitTag,
String[] commArr, String[] detailArr) throws Exception {
LinkedList list = new LinkedList();
String[] line = null;
try {
InputSource is = new InputSource(br);
DocumentBuilderFactory domfac = DocumentBuilderFactory
.newInstance();
DocumentBuilder dombuilder = domfac.newDocumentBuilder();
;
Document document = dombuilder.parse(is);
document.normalize();
HashMap commMap = new HashMap();
int commLength = commArr.length;
int detailLength = detailArr.length;
// 获取共有属性
for (int i = 0; i < commLength; i++) {
line = commArr[i].split(":");
NodeList nodelist = document.getElementsByTagName_r(line[0]);
if (line.length > 1) {
String[] attrArr = line[1].split(",");
if (attrArr == null) {
continue;
}
for (int k = 0; k < attrArr.length; k++) {
String attrValue = ((Element) nodelist.item(0))
.getAttribute(attrArr[k]);
commMap.put(attrArr[k], attrValue);
}
} else {
String ss = nodelist.item(0).getFirstChild().getNodeValue();
commMap.put(commArr[i], ss);
}
}
// 获取每个数据单元的具体信息
NodeList recordslist = document.getElementsByTagName_r(dataUnitTag);
Eelement element = null;
for (int i = 0; i < recordslist.getLength(); i++) {
HashMap detailMap = (HashMap) commMap.clone();
element = (Element) recordslist.item(i);
for (int j = 0; j < detailLength; j++) {
line = detailArr[j].split(":");
NodeList nodelist = element.getElementsByTagName_r(line[0]);
if (line.length > 1) {
String[] attrArr = line[1].split(",");
if (attrArr == null) {
continue;
}
for (int k = 0; k < attrArr.length; k++) {
String attrValue = ((Element) nodelist.item(0))
.getAttribute(attrArr[k]);
detailMap.put(attrArr[k], attrValue);
}
} else {
String ss = nodelist.item(0).getFirstChild()
.getNodeValue();
detailMap.put(detailArr[j], ss);
}
}
list.add(detailMap);
}
} catch (Exception e) {
throw new Exception("获取" + line[0] + "节点信息出错,请核查属性名称大小写是否正确!");
}
return list;
}
setEncoding(String encoding)方法。但我试了好多种编码方式多不行,于是我去查了下api,结果发现有这么一段话:
SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入。如果有字符流可用,则解析器将直接读取该流,而忽略该流中找到的任何文本编码声明。如果没有字符流,但却有字节流,则解析器将使用该字节流,从而使用在 InputSource 中指定的编码,或者另外(如果未指定编码)通过使用某种诸如 XML 规范 中的算法算法自动探测字符编码。如果既没有字符流,又没有字节流可用,则解析器将尝试打开到由系统标识符标识的资源的 URI 连接。
由上面一段话可以看出,setEncoding(String
于是我考虑:是不是在把读取的文件内容从字节流转化成字符流的时候,进行编码指定呢? 因为我们知道JDK的确提供了这样的方法,如BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
重新编译后运行,OK,正确显示出中文来了。
总结,在把字节流转化成字符流(FileInputStream变成InputStreamReader)的过程中对于TXT文本貌似是没有影响的,因为我在处理文本文件时,从来没有指定过编码方式,但utf-8下的xml文件需要指定编码方式避免中文乱码;另外,InputSource
版权申明:该文章由于本人开发遇见,一直未解,最后借于该文,十分感谢作者的无私奉献。转载该文只为了以后更加方便忘记了处理的细节。