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

前端之家收集整理的这篇文章主要介绍了几行代码搞定树形文本转XML和JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于需要将百度脑图的内容导出为xml或者json格式,发现百度脑图只能导出为树形文本,所以就写了个小应用给编辑用。


  1. /// <summary>
  2. /// 树形文本转xml
  3. /// </summary>
  4. /// <param name="txt"></param>
  5. /// <returns></returns>
  6. public static string Txt2Xml(string txt)
  7. {
  8. //创建XDocument对象
  9. var xmlDoc = new XDocument();
  10.  
  11. //逐行提取文本
  12. var txts = txt.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
  13.  
  14. foreach (var tt in txts)
  15. {
  16. var title = tt.TrimStart('\t').Trim();
  17. if (title == "") continue;
  18. var level = tt.Length - title.Length;
  19.  
  20. //父节点
  21. var parentEle = xmlDoc.Descendants("level").LastOrDefault(p => p.Value == (level - 1).ToString())?.Parent;
  22. //新节点
  23. XElement newChildEle;
  24. if (parentEle == null)
  25. xmlDoc.Add(newChildEle = new XElement("data"));
  26. else
  27. parentEle.Add(newChildEle = new XElement("children"));
  28.  
  29. newChildEle.Add(new XElement("topic",title));
  30. newChildEle.Add(new XElement("level",level));
  31. /**可以添加其它需要的内容**/
  32. //newChildEle.Add(new XElement("direction","right"));
  33. //newChildEle.Add(new XElement("expanded",true));
  34. }
  35.  
  36. xmlDoc.Declaration = new XDeclaration("1.0","UTF-8",null);
  37.  
  38. return xmlDoc.Declaration + "\r\n" + xmlDoc;
  39. }
  40. /// <summary>
  41. /// xml转json
  42. /// </summary>
  43. /// <param name="xmlTxt"></param>
  44. /// <returns></returns>
  45. public static string Xml2Json(string xmlTxt)
  46. {
  47. return JsonConvert.SerializeXNode(XElement.Parse(xmlTxt),Newtonsoft.Json.Formatting.Indented);
  48. }
  49.  
  50. public void SaveToFile(string txt,string type)
  51. {
  52. if (type == "xml")
  53. {
  54. var xmlDoc = new XmlDocument();
  55. xmlDoc.LoadXml(txt);
  56. _txtTitle = xmlDoc.DocumentElement?.SelectSingleNode("topic")?.InnerText;
  57. }
  58. else
  59. {
  60. var jo = JObject.Parse(txt);
  61. _txtTitle = jo["data"]?["topic"]?.ToString();
  62. }
  63.  
  64. var sfd = new SaveFileDialog
  65. {
  66. Filter = @"" + type + @" file|*." + type + "",FilterIndex = 2,RestoreDirectory = true,FileName = _txtTitle ?? "untitled"
  67. };
  68.  
  69. var dr = sfd.ShowDialog();
  70. if (dr == DialogResult.OK && sfd.FileName.Length > 0)
  71. {
  72. using (var fsw = new StreamWriter(sfd.FileName,false))
  73. {
  74. fsw.Write(txt);
  75. fsw.Close();
  76. fsw.Dispose();
  77. }
  78. new MessageBoxTimeOut().Show(1000,@"保存成功。",@"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
  79. }
  80. }

猜你在找的XML相关文章