Hello,
I'm using Maui app , I need to create/add/delete operations in XML.
You can use System.Xml.XmlDocument to create/add/delete operations in XML.
How I create the xml.
We can save the xml file to the string path = FileSystem.Current.AppDataDirectory + "/jobs.xml";
firstly, then you can create a <Jobs>
node in the xml and save it by Save
method.
// Create XML document
XmlDocument xmlDoc = new XmlDocument();
// Create root element
XmlElement rootElement = xmlDoc.CreateElement("Jobs");
xmlDoc.AppendChild(rootElement);
// Save the XML document to a file
xmlDoc.Save(path);
How I add new node to xml.
Before adding new node, you need to load this XML by path, then create new node by xmlDoc.CreateElement
, add attributes to the Job node and append the Job node to the root element
// Load the existing XML document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
// Create a new Job node
XmlElement jobElement = xmlDoc.CreateElement("Job");
// Add attributes to the Job node
jobElement.SetAttribute("id", "123");
// Append the Job node to the root element
xmlDoc.DocumentElement.AppendChild(jobElement);
// Save the modified XML document
xmlDoc.Save(path);
How I delete node from XML using Job id(idenatifier).
Before you delete the node, you need to load the XML as well.Then, you can get the job node by the job id, delete it by xmlDoc.DocumentElement.RemoveChild
method.
...load the XML
// Get the Job node to be deleted based on the Job ID
XmlNode jobNodeToDelete = xmlDoc.SelectSingleNode("/Jobs/Job[@id='123']");
// Check if the node exists before attempting to delete
if (jobNodeToDelete != null)
{
// Remove the Job node from the XML document
xmlDoc.DocumentElement.RemoveChild(jobNodeToDelete);
// Save the modified XML document
xmlDoc.Save(path);
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.