gpt4 book ai didi

java - Rhino AstNode toSource 方法编码为 ISO-8859-1?

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:48 24 4
gpt4 key购买 nike

我将 js 字符串解析为抽象语法树,然后更改 StringLiteral 节点的值,并且需要将整个 Ast 内容写回字符串。但是当我使用 toSource 方法时,StringLiterals 值中的特殊字符将以 ISO-8859-1 进行编码。

示例:

类测试:

public static void main(){
testString = " Assignment = 'Glück'; "

CompilerEnvirons env = new CompilerEnvirons();
AstRoot astRoot = new Parser(env).parse(testString, null, 1);

PrintVisitor visitor = new PrintVisitor();
astRoot.visitAll(visitor);
}

在 PrintVisitor 类中扩展 NodeVisitor:

@Override
public boolean visit(AstNode node) {
if (node.getClass() == StringLiteral.class){
StringLiteral sl = (StringLiteral) node;
System.out.println("value: " + sl.getValue());
System.out.println("src: " + sl.toSource());
}
}

输出:

value: Glück
src: 'Gl\xfcck"

如您所见,该值以正确的编码存储,但 toSource 方法返回转义的 ISO-8859-1 字符。

你知道有什么方法可以让 toSource 方法返回 UTF-8 吗?或者你能建议任何其他方法来逆转解析过程,这样我就可以从整个 ast 中取回纯文本吗?

我花了很多时间寻找节点或解析器的任何属性,并尝试对输出字符串进行后处理,但还没有成功。

感谢您的帮助!

最佳答案

看来StringLiteral#toSource() escapes the value .

如果您只想包含引用,请尝试:

StringLiteral sl = (StringLiteral) node;
String value = sl.getValue(true); // "Glück"

关于java - Rhino AstNode toSource 方法编码为 ISO-8859-1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com