Create XElement Recursive - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Create XElement Recursive

Demo Code


using System.Xml.Linq;
using System.Xml;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Linq;
using System.IO;/*w ww  . j  a  va  2  s  . c  o  m*/
using System.Collections.Generic;
using System;

public class Main{
        private static XElement CreateXElementRecursive(string path, object value, XElement currentLevel)
        {
            if (currentLevel.Name == "val" || path == "")
                return null;

            var dotIndex = path.IndexOf(".");
            var currentLevelKey = path.Substring(0, dotIndex < 0 ? path.Length : dotIndex);

            if (!XElementContainsChild(currentLevelKey, currentLevel))
            {
                currentLevel.Add(CreateXElementEmpty(currentLevelKey));
            }

            foreach (var i in currentLevel.Elements())
            {
                if (i.Name == "val")
                    return null;
                if (i.HasAttributes && i.Attribute("key") != null && i.Attribute("key").Value == currentLevelKey)
                {
                    if (dotIndex < 0)
                    {
                        i.Add(value);
                        return i;
                    }
                    path = path.Replace(currentLevelKey, "").TrimStart('.');
                    return CreateXElementRecursive(path, value, i);
                }
            }
            return null;
        }
}

Related Tutorials