简体   繁体   English

如何使用C#在XML中以递增名称添加节点

[英]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. 下面给出的代码用于通过右键单击WPF应用程序中具有的上下文菜单来调用添加验证的表单。

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:

<?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. 为了创建XML,我使用了以下代码。 string MyValue; 字符串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. 您可以依靠元素Count来维护新添加元素的值序列,请注意,这种方法仅在同步添加元素时有效。

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 检查这个Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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