我试图遍历xmlnodes。但得到此错误“对象引用未设置为对象的实例。”我的主要目标是通过datgridviewcell循环它,但我不知道我怎么能进一步。我知道我的网格中的字体,日期和注释的列索引。我如何循环遍历这些列索引并能够将值解析为字符串?
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="Button"xml:space="preserve">
<value></value>
<comment>[Font][/Font][DateStamp][/DateStamp[Comment][/Comment]</comment>
</data>
XmlNodeList _Nodelist = _doc.SelectNodes("/root");
foreach(XmlNode _Xnode in _Nodelist)
{
XmlNode _data = _Xnode.SelectSingleNode("data");
XmlNodeList _CommentNodes = _data.SelectNodes("comment");
if(_CommentNodes != null)
{
foreach(XmlNode node in _CommentNodes)
{
XmlNode _comment = node.SelectSingleNode("comment");
{
string _font = _comment["Font"].InnerText; //it throws the error here
string _Date = _comment["DateStamp"].InnerText;
string _Comment = _comment["Comment"].InnerText;
}
}
}
}
答案 0 :(得分:0)
你的问题是那个
<comment>
节点,但您正在寻找嵌套的comment
节点。<comment>
节点内的文字不是XML - 它只是text content。因此,它不能像parsed那样包含子XML元素。相反,您需要执行以下操作:
XmlNodeList _Nodelist = _doc.SelectNodes("/root");
foreach (XmlNode root in _Nodelist)
{
XmlNode _data = root.SelectSingleNode("data");
if (_data == null)
continue;
XmlNodeList _CommentNodes = _data.SelectNodes("comment");
foreach (XmlNode _comment in _CommentNodes)
{
var text = _comment.InnerText;
// text = "[Font][/Font][DateStamp][/DateStamp[Comment][/Comment]"
string _font = text.Between("[Font]", "[/Font]", StringComparison.Ordinal);
string _Date = text.Between("[DateStamp]", "[/DateStamp]", StringComparison.Ordinal);
string _Comment = text.Between("[Comment]", "[/Comment]", StringComparison.Ordinal);
}
}
使用扩展方法:
public static class TextHelper
{
public static string Between(this string input, string start, string end, StringComparison comparison)
{
var startIndex = input.IndexOf(start, comparison);
if (startIndex < 0)
return null;
startIndex += start.Length;
var endIndex = input.IndexOf(end, startIndex, comparison);
if (endIndex < 0)
return null;
return input.Substring(startIndex, endIndex - startIndex);
}
}
请注意,_Date
将为null,因为正如@colmde所说,"[/DateStamp"
缺少结束括号。