C# 如何处理C中的NodeSelect为nill#
好吧,我是C#的新手,但在其他语言方面经验丰富,但如果NodeSelect为nill,我不知道如何处理C# 如何处理C中的NodeSelect为nill#,c#,null,try-catch,C#,Null,Try Catch,好吧,我是C#的新手,但在其他语言方面经验丰富,但如果NodeSelect为nill,我不知道如何处理 DirectoryInfo root = new DirectoryInfo(root_path); XmlDocument xmlDoc = new XmlDocument(); //* create an xml document object. xmlDoc.Load(root_path + @"\file.xml"); //* load the XML document fr
DirectoryInfo root = new DirectoryInfo(root_path);
XmlDocument xmlDoc = new XmlDocument(); //* create an xml document object.
xmlDoc.Load(root_path + @"\file.xml"); //* load the XML document from the specified file.
//* Get elements.
XmlNodeList elements = xmlDoc.SelectNodes("//elements");
foreach (XmlNode node in elements){
string link = node.SelectSingleNode("link").InnerText.Trim();
在上面的示例中,链接可能在xml中的元素块中,也可能不在元素块中,我需要它不要给我这个错误
NULLReferenceExemption
Object reference not set to an instance of an object.
我想尝试一下接球会有用,但我知道在C语言中一定有更好的方法#
更新
var linkNode = node.SelectSingleNode("link");
if (linkNode != null)
{
string link = linkNode.InnerText.Trim();
}
Console.WriteLine("link: " + link);
错误就是错误
The name 'link' does not exist in the current context
你可以做,比如
foreach (XmlNode node in elements)
{
var linkNode = node.SelectSingleNode("link");
if (linkNode != null)
{
string link = linkNode.InnerText.Trim();
}
}
你可以做,比如
foreach (XmlNode node in elements)
{
var linkNode = node.SelectSingleNode("link");
if (linkNode != null)
{
string link = linkNode.InnerText.Trim();
}
}
正如您所说,如果
链接
节点可能在那里,也可能不在那里,那么在访问它的方法和属性之前,您必须测试它是否存在
某种
var ln = node.SelectSingleNode("link");
if (ln != null && ln.InnerText!=null)
{
string link = ln.InnerText.Trim();
...
}
正如您所说,如果
链接
节点可能在那里,也可能不在那里,那么在访问它的方法和属性之前,您必须测试它是否存在
某种
var ln = node.SelectSingleNode("link");
if (ln != null && ln.InnerText!=null)
{
string link = ln.InnerText.Trim();
...
}
取决于在值为null的情况下要做什么?我想在相关注释中将其设置为空字符串,以这种方式解析XML既困难又容易出错。相反,您应该将序列化类与序列化引擎(如DataContract或协议缓冲区)一起使用。关于这一点,有很多例子和Q/A。@Indeera-您是否有关于如何实现序列化的片段或链接…我对C不熟悉#取决于在值为null的情况下您想做什么?我想在相关注释中将其设置为空字符串,以这种方式解析XML既困难又容易出错。相反,您应该将序列化类与序列化引擎(如DataContract或协议缓冲区)一起使用。关于这一点,有很多例子和问答。@Indeera-你有关于如何实现序列化的片段或链接吗……我是C#新手,如果InnerText为null怎么办?@Willem这就是为什么在访问之前要对它进行测试的原因it@Indeera当前位置这就是为什么我应该在忘乎所以之前仔细阅读。很抱歉:)如果InnerText为空怎么办?@Willem这就是为什么在访问之前要对它进行测试的原因it@Indeera当前位置这就是为什么我应该在忘乎所以之前仔细阅读。抱歉:)如果InnerText为空怎么办?@Orsol-好的,我会在我的问题中粘贴…一秒钟,如果InnerText为空怎么办?@Orsol-好的,我会在我的问题中粘贴…一秒钟