格式化xml 给没有节点的内容添加节点

这个困扰我很长时间的问题, 终于得到了解决!!!

在很多时候我们会遇到下面这种情况的xml

<a>aaaaa<b>bbbb</b>ccccccc</a>

这种节点内含有 内容 并且还有 标签 的并且不换行

       /// <summary>
        /// 给没有节点的添加节点
        /// </summary>
        /// <param name="xElement">要处理的节点或xml</param>
        /// <param name="XName">要添加的节点名称</param>
        /// <returns></returns>
        public static XElement CreateNewEle(XElement xElement, string XName)
        {
            try
            {
                if (xElement == null || string.IsNullOrEmpty(XName))
                {
                    return null;
                }
                else
                {
                    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();

                    XElement xElement1 = xElement;

                    foreach (var item in xElement.Elements())
                    {
                        string guid = Guid.NewGuid().ToString();
                        xElement1 = XElement.Parse(xElement1.ToString().Replace(item.ToString(), "|" + guid + "|"));
                        keyValuePairs.Add(guid, item.ToString());
                    }

                    var splits = xElement1.Value.Split('|');
                    for (int i = 0; i < splits.Count(); i++)
                    {
                        Guid.TryParse(splits[i], out Guid aaa);
                        if (Guid.Empty != aaa)
                        {
                            splits[i] = keyValuePairs[aaa.ToString()];
                        }
                    }
                    XElement element = new XElement(xElement.Name);

                    xElement.Attributes().ToList().ForEach(e => element.SetAttributeValue(e.Name, e.Value));
                    foreach (var item in splits)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            if (item.Contains("/"))
                            {
                                element.Add(XElement.Parse(item));
                            }
                            else
                            {
                                element.Add(new XElement(XName, item));
                            }
                        }
                    }
                    xElement = element;
                }
                return xElement;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

这个方法可以完美解决,有点麻烦,有更好的思路欢迎评论!!!

猜你喜欢

转载自www.cnblogs.com/mi21/p/12933004.html