我试图使用xml-rs库读取生锈中的XML文件。但是,当读取文件时,它会对消息:Unexpected characters outside the root element感到恐慌。
我发现这是因为文件中存在'BOM‘(字节顺序标记)。我如何摆脱这个BOM,这样我才能读取我的文件?该库的作者引用了另一个库bom_remover,我在任何地方都找不到它。
发布于 2021-11-21 10:49:50
下面是我如何做到这一点的:
的文件
为了检测文件是否有BOM,我使用了unicode-bom库(unicode-bom = "1.1.4"在cargo.toml依赖项中)。
// detect BOM
let bom = getbom(&filepath);
let file = File::open(&filepath).unwrap();
let mut reader = BufReader::new(file);
// skip BOM (for now assume always 3 bytes)
if bom != Bom::Null {
let mut x = [0; 3];
let _y = reader.read_exact(&mut x);
}
// Parse file using - in this example - the georust/gpx library (which requires a BufReader)
let res: Result<Gpx, GpxError> = read(reader);加上一个打开文件的简单函数,获取bom信息并再次关闭它:
fn getbom(path: &str) -> Bom {
let mut file = File::open(path).unwrap();
Bom::from(&mut file)
}这段代码也可以通过处理2字节的BOM来改进&当然,也是正确的错误处理。
https://stackoverflow.com/questions/70053706
复制相似问题