以下代码抛出
System.NullReferenceException
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "XML-Datei auswählen";
ofd.Filter = "XML-Dateien|*.xml";
ofd.InitialDirectory = @"C:\";
if (ofd.ShowDialog() == DialogResult.OK)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ofd.FileName);
foreach (XmlNode node in xDoc.SelectNodes("People/Person"))
{
int age = int.Parse(node.Attributes["Age"].Value);
MessageBox.Show((age + 1).ToString());
}
}
}
错误发生在
行中age = int.Parse(node.Attributes["Age"].Value);
在本地窗口中,我可以看到,attribut" Age"保持为空。
.xml文件的结构如下:
<People>
<Person>
<Name>TestPeron</Name>
<Age>29</Age>
<Email>me@testmail.com</Email>
</Person>
</People>
&#13;
谢谢!
答案 0 :(得分:0)
该名称没有属性,只有一个元素。
答案 1 :(得分:0)
int age = int.Parse(node["Age"].InnerText)
答案 2 :(得分:0)
试试这个
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string input =
"<People>" +
"<Person>" +
"<Name>TestPeron</Name>" +
"<Age>29</Age>" +
"<Email>me@testmail.com</Email>" +
"</Person>" +
"</People>";
XDocument doc = XDocument.Parse(input);
foreach(XElement person in doc.Descendants("Person"))
{
string message = string.Format("Name : {0}, Age : {1}, Email : {2}",
person.Element("Name").Value,
person.Element("Age").Value,
person.Element("Name").Value);
MessageBox.Show(message);
Console.ReadLine();
}
}
}
}
答案 3 :(得分:0)
您正在尝试使用基本上为null对象的对象。因此,使用try和catch来处理空引用异常并查看问题是否解决