我正在尝试创建一个从用户输入生成xml文件的应用程序,这是通过2个表单完成的,主表单已经成为xml文档的基础,现在我希望从另一个xml填充“成员”正在以另一种形式创建。但是我的问题是我不想按下按钮来创建一个新的xml文件,每次我点击它添加一个成员,所以我有form_load中的基本部分,但是由于错误,我无法从按下按钮访问xml文件“ “xmlMembers”名称在当前上下文中不存在“ 代码如下:
private void btnAdd_Click(object sender, EventArgs e)
{
XmlNode member = xmlMembers.CreateElements("member"); //Causes error
XmlAttribute attID = xmlMembers.CreateAttribute("id"); //Causes error
attID.Value = MPlayID;
member.Attributes.Append(attID);
XmlAttribute attNick = XmlMembers.CreateAttribute("nick"); //Causes error
attNick.Value = MNick;
member.Attributes.Append(attNick);
}
private void Form_Member_Load(object sender, EventArgs e)
{
XmlDocument xmlMembers = new XmlDocument();
XmlNode rootNode = xmlMembers.CreateElement("members");
xmlMembers.AppendChild(rootNode);
}
答案 0 :(得分:1)
您的xmlMembers不需要以表单load:
声明 class YourClass
{
XmlDocument xmlMembers = null;
private void btnAdd_Click(object sender, EventArgs e)
{
if (xmlMembers != null)
{
XmlNode member = xmlMembers.CreateElements("member"); //Causes error
XmlAttribute attID = xmlMembers.CreateAttribute("id"); //Causes error
attID.Value = MPlayID;
member.Attributes.Append(attID);
XmlAttribute attNick = xmlMembers.CreateAttribute("nick"); //Causes error
attNick.Value = MNick;
member.Attributes.Append(attNick);
}
}
private void Form_Member_Load(object sender, EventArgs e)
{
xmlMembers = new XmlDocument();
XmlNode rootNode = xmlMembers.CreateElement("members");
xmlMembers.AppendChild(rootNode);
}
}