加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

几行代码搞定树形文本转XML和JSON

发布时间:2020-12-16 08:03:04 所属栏目:百科 来源:网络整理
导读:由于需要将百度脑图的内容导出为xml或者json格式,发现百度脑图只能导出为树形文本,所以就写了个小应用给编辑用。 /// summary /// 树形文本转xml /// /summary /// param name="txt"/param /// returns/returns public static string Txt2Xml(string txt)
由于需要将百度脑图的内容导出为xml或者json格式,发现百度脑图只能导出为树形文本,所以就写了个小应用给编辑用。


/// <summary>
        /// 树形文本转xml
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string Txt2Xml(string txt)
        {
            //创建XDocument对象
            var xmlDoc = new XDocument();

            //逐行提取文本
            var txts = txt.Split(new[] { 'r','n' },StringSplitOptions.RemoveEmptyEntries);

            foreach (var tt in txts)
            {
                var title = tt.TrimStart('t').Trim();
                if (title == "") continue;
                var level = tt.Length - title.Length;

                //父节点
                var parentEle = xmlDoc.Descendants("level").LastOrDefault(p => p.Value == (level - 1).ToString())?.Parent;
                //新节点
                XElement newChildEle;
                if (parentEle == null)
                    xmlDoc.Add(newChildEle = new XElement("data"));
                else
                    parentEle.Add(newChildEle = new XElement("children"));

                newChildEle.Add(new XElement("topic",title));
                newChildEle.Add(new XElement("level",level));
                /**可以添加其它需要的内容**/
                //newChildEle.Add(new XElement("direction","right"));
                //newChildEle.Add(new XElement("expanded",true));
            }

            xmlDoc.Declaration = new XDeclaration("1.0","UTF-8",null);

            return xmlDoc.Declaration + "rn" + xmlDoc;
        }
   	/// <summary>
        /// xml转json
        /// </summary>
        /// <param name="xmlTxt"></param>
        /// <returns></returns>
  public static string Xml2Json(string xmlTxt)
        {
            return JsonConvert.SerializeXNode(XElement.Parse(xmlTxt),Newtonsoft.Json.Formatting.Indented);
        }

public void SaveToFile(string txt,string type)
        {
            if (type == "xml")
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(txt);
                _txtTitle = xmlDoc.DocumentElement?.SelectSingleNode("topic")?.InnerText;
            }
            else
            {
                var jo = JObject.Parse(txt);
                _txtTitle = jo["data"]?["topic"]?.ToString();
            }

            var sfd = new SaveFileDialog
            {
                Filter = @"" + type + @" file|*." + type + "",FilterIndex = 2,RestoreDirectory = true,FileName = _txtTitle ?? "untitled"
            };

            var dr = sfd.ShowDialog();
            if (dr == DialogResult.OK && sfd.FileName.Length > 0)
            {
                using (var fsw = new StreamWriter(sfd.FileName,false))
                {
                    fsw.Write(txt);
                    fsw.Close();
                    fsw.Dispose();
                }
                new MessageBoxTimeOut().Show(1000,@"保存成功。",@"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读