我想要在js脚本里将xml转换为json格式,技术上可以使用C#的System.Xml.Linq.XDocument.Parse和Newtonsoft.Json.JsonConvert.SerializeXNode来实现,但是需要导入对应的程序集(即下面C#代码中高亮部分):
using System.Windows.Forms;
using Newtonsoft.Json;
using Jint;
public static void Exec(Quicker.Public.IStepContext context)
{
var engine = new Engine(cfg => cfg.AllowClr(
typeof(System.Xml.Linq.XDocument).Assembly,
typeof(Newtonsoft.Json.JsonConvert).Assembly
));
var json = engine
.Evaluate(@"
var Newtonsoft = importNamespace('Newtonsoft')
result = Newtonsoft.Json.JsonConvert.SerializeXNode(System.Xml.Linq.XDocument.Parse('<a></a>'))
");
MessageBox.Show(json.ToString());
}
(上面的脚本在Quicker中运行会弹窗{"a":""})
但是目前Quicker的 运行javascript脚本 模块默认加载的程序集中没有包括我所需的这两个类和命名空间,因此用 运行javascript脚本 模块运行以下代码:
function exec(){
var Newtonsoft = importNamespace('Newtonsoft')
Newtonsoft.Json.JsonConvert.SerializeXNode(System.Xml.Linq.XDocument.Parse('<a></a>'))
alert(x)
}
会报错Invalid generic type parameter on System.Xml.Linq.XDocument.Parse, if this is not a generic type / method, are you missing a lookup assembly?
(----test:运行Javascript代码----)
希望可以增加一个选项,能够指定要导入的额外的程序集。
另外是目前 运行javascript脚本 无法在js脚本中捕获C#函数异常,调用C#函数出错后会直接中止运行,例如这段代码
function exec(){
try{
System.IO.Path.Combine("<","a");
}catch{}
alert(1)
}
会因为System.IO.Path.Combine("<","a")报错路径中具有非法字符。直接停止,后面的alert(1)无法运行。
Jint可以通过使用CatchClrExceptions来让js引擎能够捕获.NET异常(创建时指定new Engine(cfg => cfg.AllowClr().CatchClrExceptions(exception => true));),希望能够在这个模块添加一个选项,或者直接把js捕获.NET异常设为默认行为