我使用HtmlAgilityPack
爲了從谷歌翻譯的信息抓取翻譯程序。我已經下載了HtmlAgilityPack
dll,並在我的程序中成功引用了它。我在Unity中使用Assembly。下面是我對兩個程序代碼:NullReferenceException與C#中的HtmlDocument引用#
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)
我已經嘗試更改代碼,查找解決方案,API爲HtmlDocument
,以及如何修復NullReferenceExceptions
,但由於某種原因,我無法弄清楚爲什麼我得到一個NullReferenceException
。這個問題一直困擾我一兩個禮拜,我需要繼續我的項目。任何幫助將不勝感激!
Document.SelectSingleNode不會編譯,因爲SelectSingleNode不是有效的方法。它需要DocumentNode才能訪問SelectSingleNode。 –
@CameronBarge對不起,錯字。我只是想在開頭添加一個點。 –