我试图从1个numericUpDown和3个文本框中写入数据到一个xml文件。但是,我无法跨方法访问XDocument文件的元素。C#写入xml文件元素访问问题
下面是我的代码和我所有的评论。你能帮助一个完整的noob到XML和网站?所有改进建议欢迎!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Xml.Linq;
namespace AA
{
public partial class Form1 : Form
{
//Will be used to check if the file exists in the save directory
byte ifexists = 0;
//method for file creation
public void fileCreate()
{
XDocument XDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement("Group",
new XElement("A"),
new XElement("B"),
new XElement("C"),
new XElement("D")
));
}
//method for file save (want to save 4 values from 1 numericUpDown and 3 textboxes, when I solve file creation problems I want to use numericUpDown value as an ID and load relevant info from the xml file
public void fileSave()
{
//i tried to use serverpath which seems to be better but i couldn't get it to work so I used Application.StartupPath....
XDocument XDoc = XDocument.Load(Application.StartupPath + "\\..\\File.xml");
Group.Add(new XElement("A", nUDforA.Value));
Group.Add(new XElement("B", tBforB.Text));
Group.Add(new XElement("C", tBforC.Text));
Group.Add(new XElement("D", tBforD.Text));
XDoc.Add(Group);
XDoc.Save(Application.StartupPath + "\\..\\File.xml");}
public Form1()
{
InitializeComponent();
}
//this label is used to write "Saved!"after clicking the "Write" button and become invisible again after 1 second timertick
private void Form1_Load(object sender, EventArgs e)
{
//this label is used to write "Saved!"after clicking the "Write" button and become invisible again after 1 second timertick
lblSituation.Visible = false;
}
private void btnWrite_Click(object sender, EventArgs e)
{
//first check if the file exists
if (File.Exists(Application.StartupPath +"\\..\\File.xml"))
{
ifexists = 1;
fileSave();
}
if (ifexists==0)
{
fileCreate();
fileSave();
}
//saying the user that the file is saved
lblSituation.Visible = true;
lblSituation.Text = "Saved!";
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
lblSituation.Visible = false;
timer1.Enabled = false;
}
}
}
你的'fileCreate'方法实际上并不保存文件,也不返回'XDocument'。你的'fileSave'方法加载一个'Dosya.xml'文件,但将其保存为'File.xml'。你的写方法检查是否存在'File.xml'。 –
我已将我的帖子编辑为“Dosya.xml> File.xml”。这是一个翻译错误,对不起。 @DaveZych – user3242180