使用SelectSingleNode处理Null异常

时间:2017-08-02 04:33:04

标签: c# xml xpath

无法确定以下代码和数据的问题。它返回“NullReferenceException未处理”

代码:

propertyGrid1.PropertySort = PropertySort.NoSort;

数据文件:

curl -XPOST 'http://<my_host_name>:9201/_bulk?pretty' -H 'Content-Type: application/json' -d '{ "create" : { "_index" : "my_index", "_type" : "my_document_type", "_id" : "1"} }{"id" : "AAA" , "name" : "AAAAAAAAAAAAAA"}{ "create" : { "_index" : "my_index", "_type" : "my_document_type", "_id" : "2"} }{"id" : "BBB" , "name" : "BBBBBBBBBBBBBBB"}{ "create" : { "_index" : "my_index", "_type" : "my_document_type", "_id" : "3"} }{"id" : "CCC" , "name" : "CCCCCCCCCCCCCCCC"}{ "create" : { "_index" : "my_index", "_type" : "my_document_type", "_id" : "4"} }{"id" : "DDD" , "name" : "DDDDDDDDDDDDDDDDDD"}{ "create" : { "_index" : "my_index", "_type" : "my_document_type", "_id" : "5"} }{"id" : "EEE" , "name" : "EEEEEEEEEEEEEEEEEE"}'

我试过了

XmlDocument doc = new XmlDocument();
doc.Load(Filename1);

XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("temp","http://www.Rahiman.com");

string name1 = doc.SelectSingleNode("//temp:Company/temp:Businesscard[2]/temp:Name", mgr).
    InnerText;

Console.WriteLine(name1);

以及

感谢。

2 个答案:

答案 0 :(得分:2)

检索?.标记时,它区分大小写,因此应为string name1 = doc.SelectSingleNode("//temp:Company/temp:Businesscard[2]/temp:name", mgr)?.InnerText;

{{1}}

您还可以使用{{1}} null传播:

{{1}}

答案 1 :(得分:0)

嗯,它不能是string name1; var n = doc.DocumentElement.SelectSingleNode("//temp:Company/temp:Businesscard[2]/temp:Name", mgr); if(n!=null) name1 = n.InnerText; 为空,所以它必须是Name方法调用的结果为空。在您确定它不为空之前,请不要参考name属性:

"//temp:Company/temp:Businesscard[2]/temp:name"