为什么我的XmlReader.GetAttribute()没有返回值?

时间:2010-02-28 00:31:17

标签: c# .net xml xmlreader

我正在尝试用C#解析我的XML。

以下是相关文件的一部分:

<holder name="wnd_login" width="300" x="20" height="180">...</holder>

这是应该读取它的代码:

while (reader.Read())
{
    if (reader.IsStartElement())
    {
        switch (reader.Name)
        {
            case "holder":
                Holder holder = new Holder(reader.GetAttribute("name"));
                ...
        }
    }
}

我读到这一点,常见的错误是忘记检查元素是否是一个开始元素。我添加了它,但GetAttribute仍然返回null。有什么想法吗?

1 个答案:

答案 0 :(得分:-4)

也许你需要首先使用XPath表示法来获取XmlNodes,然后像这样迭代遍历XmlNodes:

foreach(XmlNode node in XmlNodes){
     if (node["holder"].HasAttribues != null && node["holder"].Attributes.Count >1){
        for (int i = 0; i < node["holder"].Attributes.Count; i++){
             try{
                XmlAttribute attr = node["holder"].Attributes[i];
                if (attr != null){
                     ....
                }
             }catch(XmlException xmlEx){
                // Do something here with this...output to log?
             }
        }
     }
}

希望这有帮助, 最好的祝福, 汤姆。

相关问题