我正在使用HtmlAgilityPack
为了从谷歌翻译中刮取信息用于翻译程序。我已经下载了HtmlAgilityPack
dll,并在我的程序中成功引用了它。我在 Unity 中使用 Assembly。下面是我的两个程序的代码:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using HtmlAgilityPack;
public class GUIScript : MonoBehaviour {
private string textField = "";
private string input;
public Texture2D icon;
Dictionary search;
Encoding code;
// Use this for initialization
void Start () {
search = new Dictionary();
input = " ";
code = Encoding.UTF8;
//This is what is run to translate
print (search.Translate("Hola","es|en",code));
}
// Update is called once per frame
void Update () {
}
void OnGUI(){
textField = GUI.TextField(new Rect(0, Screen.height -50, Screen.width-80, 40), textField);
if(GUI.Button(new Rect(Screen.width-80, Screen.height -50, 80,40), icon)){
input = textField;
textField = "";
}
//GUI.Label(new Rect(0,Screen.height -70, Screen.width-80,20), search.Translate("Hola","es|en",code));
//print (search.Translate("Hola","es|en",code));
}
}
这是引用我的Dictionary
类的代码,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using System.Collections;
using System.Net;
using HtmlAgilityPack;
public class Dictionary{
string[] formatParams;
HtmlDocument doc;
public Dictionary(){
formatParams = new string[2];
doc = new HtmlDocument();
}
public string Translate(String input, String languagePair, Encoding encoding)
{
formatParams[0]= input;
formatParams[1]= languagePair;
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", formatParams);
string result = String.Empty;
using (WebClient webClient = new WebClient())
{
webClient.Encoding = encoding;
result = webClient.DownloadString(url);
}
doc.LoadHtml(result);
return doc.DocumentNode.SelectSingleNode("//span[@title=input]").InnerText;
}
// Use this for initialization
void Start () {
}
}
运行此程序时,我收到错误:
NullReferenceException: Object reference not set to an instance of an object
Dictionary.Translate (System.String input, System.String languagePair,System.Text.Encoding encoding) (at Assets/Dictionary.cs:32)
GUIScript.Start () (at Assets/GUIScript.cs:22)
我已经尝试更改代码、查找解决方案、APIHtmlDocument
以及如何修复NullReferenceExceptions
,但由于某种原因,我无法弄清楚为什么我会得到一个NullReferenceException
. 这个问题已经阻碍了我一两个星期,我需要继续我的项目。任何帮助将不胜感激!