简体   繁体   中英

How to add nodes inside an XML with incremented names using C#

Given below code is used to call the form for adding validation by right clicking on the context menu that i have in my WPF application.

public void AddValidation(object sender, RoutedEventArgs e)
        {
            ValidationForm obj = new ValidationForm();
            ProcessGrid.Content = obj.VForm;
        }

It will open the validation form. After entering the required details, when i click on submit button given inside the form, it will create a xml like this:-

<?xml version="1.0" encoding="utf-8"?>
<Processes>
  <Process Name="Process1" Namespace="" Methodname="">
    <Validations IsSelected="True" />
       <validation>xsdPath</validation>
    <Validations>
</Process>
</Processes>

If i will again add any new validation then it will again add a node in this way.

<?xml version="1.0" encoding="utf-8"?>
<Processes>
  <Process Name="Process1" Namespace="" Methodname="">
    <Validations IsSelected="True" />
       <validation>xsdPath</validation>
       <validation>xsdPath1</validation>
    <Validations>
</Process>
</Processes>

For creating XML, i have used the following code. string MyValue;

MyValue = Pages.ProcessesLayoutList.MyValue;
XDocument doc = XDocument.Load(@"C:\Users\562630\Desktop\New folder\ProcessComplete.xml");
var a = doc.Descendants("Process").Where(x => (string)x.Attribute("Name") == MyValue).
Select(x => x.Element("Validations")).FirstOrDefault();
a.Add(new XElement("Validation", s));
doc.Save(@"C:\Users\562630\Desktop\New folder\ProcessComplete.xml");

But, i want to add node with incremented names like then and so on.So, After adding validation nodes each and every time, it should add validation node in incremental order. Please suggest some way to do so. Thanks in advance.

You could rely on Count of elements to maintain value sequence for newly added elements, please note this approach works only if you add elements synchronously.

var count = 
        doc.Descendants("Validations")
        .Elements()
        .Count();

// Use count to maintain incremental value for your newly added elements.   
doc.Descendants("Validations")
        .First()
        .Add(new XElement("validation", string.Format("xsdPath{0}", count)));   

Check this Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM