前端之家收集整理的这篇文章主要介绍了
几行代码搞定树形文本转XML和JSON,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于需要将百度脑图的内容导出为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 + "\r\n" + 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);
}
}
原文链接:https://www.f2er.com/xml/293349.html