简体   繁体   中英

C#: Creating XML document using Linq having not proper output?

I'm trying to create xml data from my data, creation was successfull but the output is bad how can I fix this issue?

Here is my code:

private void btnGenerate_Click(object sender, EventArgs e)
    {
        XElement xml = new XElement("Navigation",
            new XElement("NavigationSets"));
        foreach (DataRow row_navs in GetNavigationSets().Rows)
        {
            xml.Add(new XElement("NavigationName", row_navs["name"].ToString()));
            foreach (DataRow row_sets in GetMenusInNavigationSetByNavigation(2).Rows)
            {
                if (int.Parse(row_sets["id"].ToString()) == int.Parse(row_navs["id"].ToString()))
                {
                    foreach (DataRow row_menus in GetMenuById(int.Parse(row_sets["menu_id"].ToString())).Rows)
                    {
                        xml.Add(new XElement("MenuName", row_menus["name"].ToString()));
                    }
                }
            }
        }
        xml.Save("data.xml");
    }

Im expecting an output like this

    <?xml version="1.0" encoding="utf-8"?>
<Navigation>
    <NavigationSets>
        <NavigationName>
            <MenuName></MenuName>
        </NavigationName>
    <NavigationSets/>
</Navigation>

In my current code my output is like this

  <?xml version="1.0" encoding="utf-8"?>
<Navigation>
    <NavigationSets/>
        <NavigationName></NavigationName>
    <MenuName></MenuName>
</Navigation>

To add to Jon Skeets answer,

You can also use

using System.Xml.Linq;

to loop through lists so it is all one statement,

new XElement("NavigationSets",
    menus.Select(menu => new XElement("MenuName"))
)

Look at when you're adding elements:

xml.Add(new XElement("NavigationName", row_navs["name"].ToString()));
xml.Add(new XElement("MenuName", row_menus["name"].ToString()));

Where xml is this element:

XElement xml = new XElement("Navigation",
           new XElement("NavigationSets"));

That means xml is the Navigation element, not the NavigationSets element. I suspect you want something like:

XElement outer = new XElement("Navigation");
XElement inner = new XElement("NavigationSets");
outer.Add(inner);

... then add to inner .

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