我試圖從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