简体   繁体   中英

Converting xml tree to json tree

Here's my code which succesfully creates XML:

XDocument xdoc = new XDocument();
XElement root = new XElement("tree");
root.Add(new XAttribute("id", 0));
xdoc.Add(root);

new BuildFoldersTree(root, db);

var items = (from x in db.Items orderby x.name select new { x.name, x.id, x.parent }).ToList();
foreach (var p in items)
{
    XElement e = new XElement("item",
        new XAttribute("text", p.name),
        new XAttribute("id", p.id),
        new XAttribute("parentId", p.parent));
    XElement parent = root.XPathSelectElement(String.Format("//*[@id=\"FOLDER_{0}\"] ", p.parent.ToString()));
    if (parent != null) parent.Add(e);
 }

and:

public void BuildFoldersTree(XElement root, MyEntities db)
{
    List<Folder> folders = (from x in db.Folders orderby x.parent select x).ToList();

    for (int i = 0; i < folders.Count; i++)
    {
        int f_id = folders[i].parent;
        Folder folder = folders[i];

        XElement e = new XElement("item",
            new XAttribute("text", folder.name),
            new XAttribute("id", "FOLDER_" + folder.id.ToString()),
            new XAttribute("parentId", folder.parent));

        if (folder.parent == 0)
        {
            root.Add(e);
        }
        else
        {
            XElement parent = root.XPathSelectElement(String.Format("//*[@id=\"FOLDER_{0}\"] ", folder.parent.ToString()));
             parent.Add(e);
        }
    }
}

Here's what's going on there: I have two tables in my database. One for Folders, and one for Items. Each item has a parent folder. The item has a column 'parent' which is integer and which represents the folder id. But, each folder also has a parent. The folder has a column named 'parent' which is integer and which represents an id of another folder.

With that code, I'm creating an xml tree with folders, and then I add the items to the correct folder.

The previous code works.

Now, I need to make the same algorithm but for Json. So, it won't use Xml, it should create a Json tree.

I have no idea on how to begin. What should I use?

Here's an example of what the result xml looks like:

<tree id="0">
    <item text="Folder_name" id="FOLDER_1" parentId="0">
        <item text="Other folder name" id="FOLDER_96" parentId="1">
            <item text="Third folder name" id="FOLDER_127" parentId="96">
                <item text="New folder" id="FOLDER_147" parentId="127" />
                <item text="item name" id="959" parentId="147" />
                <item text="item name sdgdfh" id="1152" parentId="147" />
            </item>
        </item>
    </item>
</tree>

There is functionality in the JSON.NET library for this. You can use the SerializeXmlNode method of the JsonConvert class contained in the JSON.NET library. Your code would look as follows:

var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(xmlDocument);

You can find more information here: http://james.newtonking.com/projects/json/help/index.html?topic=html/ConvertingJSONandXML.htm

If we apply this to your example, we have the following:

string xml = "<tree id=\"0\">" +
                        "<item text=\"Folder_name\" id=\"FOLDER_1\" parentId=\"0\">" +
                            "<item text=\"Other folder name\" id=\"FOLDER_96\" parentId=\"1\">" +
                                "<item text=\"Third folder name\" id=\"FOLDER_127\" parentId=\"96\">" +
                                    "<item text=\"New folder\" id=\"FOLDER_147\" parentId=\"127\" />" +
                                    "<item text=\"item name\" id=\"959\" parentId=\"147\" />" +
                                    "<item text=\"item name sdgdfh\" id=\"1152\" parentId=\"147\" />" +
                                "</item>" +
                            "</item>" +
                        "</item>" +
                    "</tree>";

var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(xmlDocument);

The json variable now contains the following data:

{
  "tree":{
  "@id":"0",
  "item":{
     "@text":"Folder_name",
     "@id":"FOLDER_1",
     "@parentId":"0",
     "item":{
        "@text":"Other folder name",
        "@id":"FOLDER_96",
        "@parentId":"1",
        "item":{
           "@text":"Third folder name",
           "@id":"FOLDER_127",
           "@parentId":"96",
           "item":[
              {
                 "@text":"New folder",
                 "@id":"FOLDER_147",
                 "@parentId":"127"
              },
              {
                 "@text":"item name",
                 "@id":"959",
                 "@parentId":"147"
              },
              {
                 "@text":"item name sdgdfh",
                 "@id":"1152",
                 "@parentId":"147"
              }
           ]
        }
     }
  }
}

This is a JSON representation of your XML document.

我认为最简单的方法是使用Json.Net并将XDocument序列化为json。

var jsonstr = JsonConvert.SerializeXNode(xdoc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM