我尝试更新一些属性使用jdom2值现有的XML文件。当我创建XML文件,我发现了utf8编码问题。
属性值是"1 student Noun".
但我在输出中看到的值是:
1	student	Noun
我写的代码如下所示:
SAXBuilder builder = new SAXBuilder();
Document document = document = builder.build(filePath);
Element root = document.getRootElement();
for(Element sentenceElement : root.getChildren("sentence")){
String transcriptionText = "";
for(Element transcriptionElement : sentenceElement.getChildren("transcription")){
for(Element wordElement : transcriptionElement.getChildren("word")){
transcriptionText += " "+wordElement.getAttributeValue("text");
}
transcriptionParser = ParserUtil.getResponse(transcriptionText);
transcriptionElement.getAttribute("text").setValue(transcriptionText);
transcriptionElement.getAttribute("parser").setValue(transcriptionParser);
}
for(Element translationElement : sentenceElement.getChildren("translation")){
translationParser = getResponse(translationElement.getAttributeValue("text"));
translationElement.getAttribute("parser").setValue(translationParser);
}
}
Format format = Format.getPrettyFormat();
XMLOutputter xmlOutput = new XMLOutputter(format);
/*try (OutputStream out = new FileOutputStream(filePath)) {
xmlOutput.output(document, out);
}catch(Exception e){
e.printStackTrace();
}
}*/
xmlOutput.output(document, Files.newBufferedWriter(Paths.get(filePath),StandardCharsets.UTF_8));
我用这两个选项:
xmlOutput.output(document, Files.newBufferedWriter(Paths.get(filePath),StandardCharsets.UTF_8));
和
try (OutputStream out = new FileOutputStream(filePath)) {
xmlOutput.output(document, out);
}catch(Exception e){
e.printStackTrace();
}
但是,他们都没有得到解决的问题。如何解决这个问题呢?
该字符串"1 student Noun"
显然包含了词与词之间的制表符。
因此,如果XML输出包含1	student	Noun
这就是完全确定。的制表符具有Unicode值9和	
是表示一个正确的XML实体。