C# 读取XML文件会导致索引超出范围异常
使用C#我有一个XML文件,如C# 读取XML文件会导致索引超出范围异常,c#,xml,C#,Xml,使用C#我有一个XML文件,如 <?xml version="1.0" encoding="utf-8"?> <root> <Account> <name>Jani</name> </Account> </root> 但我得到的索引超出范围错误如下: 为什么会发生这种情况?您正在尝试读取节点.Attributes[0].Value但示例XML文件中没有属性。不确定确切的语法,但它可能更接近您试
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
但我得到的索引超出范围错误如下:
为什么会发生这种情况?您正在尝试读取
节点.Attributes[0].Value
但示例XML文件中没有属性。不确定确切的语法,但它可能更接近您试图读取的node.Attributes[0]。Value
节点。但是示例XML文件中没有attribtue。不确定确切的语法,但可能更接近node.Value
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
节点
是您的根节点。看起来是这样的:
<root>
节点。属性[0]
引用第一个属性。没有第一个属性,也没有第二个属性——您根本没有在XML中使用属性。因此,这超出了范围。空集合中没有第一项
您需要的是一个名为name
的元素,它位于XML树的较低位置
可能是这样的:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
然后您需要查看节点.InnerText
,从中获取“Jani”
节点
是您的根节点。看起来是这样的:
<root>
节点。属性[0]
引用第一个属性。没有第一个属性,也没有第二个属性——您根本没有在XML中使用属性。因此,这超出了范围。空集合中没有第一项
您需要的是一个名为name
的元素,它位于XML树的较低位置
可能是这样的:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
然后您需要查看
节点。InnerText
以从中获取“Jani”
。正如其他答案所述,您当前的XML没有属性
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
如果您的XML确实有属性
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
正如其他答案所提到的,您当前的XML没有属性
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
如果您的XML确实有属性
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
您需要的是
元素
,而不是属性
。发生在我身上:你需要元素
,而不是属性
。发生在我身上:谢谢,我现在没有收到任何错误,但结果是空的。标签上没有显示任何内容@MonaCoder我刚刚修复了答案中的一个错误:节点。值
错误。我应该把它改为node.InnerText
。您是否尝试了InnerText
?谢谢Ed,我现在没有收到任何错误,但结果是空的。标签上没有显示任何内容@MonaCoder我刚刚修复了答案中的一个错误:节点。值
错误。我应该把它改为node.InnerText
。您是否尝试了InnerText
?