Saya memiliki kode ini yang berfungsi dengan baik, tetapi sepertinya saya tidak tahu cara menyimpan pembaruan XML.descendents list = JobNames ke dokumen XML.

public void ProcessJobNames(String JobName = null, Boolean rRemove = false)
    {

        System.Xml.Linq.XDocument xml = System.Xml.Linq.XDocument.Load(_JobPath + @"\" + _ConfigFile);
        var JobNames = xml.Descendants("setting").Where(xe => xe.Attribute("key").Value.Contains("JobType")).ToList();

        System.Xml.Linq.XElement copyXE = null;


        int JobCount = 0;

        foreach (System.Xml.Linq.XElement strJobName in JobNames)
        {
            //strJobNames.Add(strJobName.LastAttribute.Value.ToString());
            JobCount = JobCount + 1;
            strJobName.FirstAttribute.Value = "JobType" + (JobCount).ToString();

            copyXE = strJobName; // Make a copy of the Job

            // Check if the JobName is in the Job Processor to be Removed
            if ((JobName != null) && (rRemove == true) && (strJobName.LastAttribute.Value.ToString().Contains(JobName)))
            {
                // Remove the Job from the Configuration File
                strJobName.Remove();
                JobCount = JobCount - 1;
            }
            // Check if the JobName is in the Job Processor to be Added
            if ((JobName != null) && (rRemove == false) && (strJobName.LastAttribute.Value.ToString().Contains(JobName)))
            {
                // Add the Job from the Configuration File
                strJobName.Remove();
                JobCount = JobCount - 1;
            }
        }

        // Add the new Job
        if ((JobName != null) && (rRemove == false)) {
            File.Copy(_RulesFolder + cmboRules.Text, _JobPath + cmboRules.Text);

            System.Xml.Linq.XElement newJob = new System.Xml.Linq.XElement(copyXE);
            newJob.FirstAttribute.Value = "JobType" + (JobCount + 1).ToString();
            newJob.LastAttribute.Value = _JobPrefix + cmboRules.Text;

            copyXE.Parent.Add(newJob)

        }

        // Save the XML Configuration File
        xml.Save(_JobPath + _ConfigFile);

    }

Saya pikir saya kehilangan sesuatu setelah "JobNames.Add(newJob)" untuk memperbarui keturunan dalam dokumen XML.

0
PigsIncorporated 20 September 2019, 23:12

1 menjawab

Jawaban Terbaik

Untuk menambahkan node di runtime, Anda bisa menggunakan XElement.Parent.Add()metode untuk menambahkan anak. Sebagai contoh,

foreach(var job in jobList)
{
    if(job.Attribute("name").Value == "job1")  //Any condition on which new node is to be added
    {
        var copy = job;
        copy.Attribute("name").Value = "job3";
        job.Parent.Add(copy);
    }
}

Sampel

Memasukkan

<root>
  <jobs>
    <job name="job1"></job>
    <job name="job2"></job>
  </jobs>
</root>

Keluaran

<root>
  <jobs>
    <job name="job3"></job>
    <job name="job2"></job>
    <job name="job3"></job>
  </jobs>
</root>
1
Anu Viswan 21 September 2019, 02:20