繁体   English   中英

C#:使用Linq创建XML文档时输出不正确?

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

我正在尝试从我的数据创建xml数据,创建成功,但是输出结果不好,我该如何解决此问题?

这是我的代码:

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");
    }

我期待这样的输出

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

在我当前的代码中,我的输出是这样的

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

要添加到Jon Skeets答案中,

您也可以使用

using System.Xml.Linq;

遍历列表,所以这只是一条语句,

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

查看添加元素的时间:

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

xml是此元素:

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

这意味着xmlNavigation元素, 而不是 NavigationSets元素。 我怀疑您想要类似的东西:

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

...然后添加到inner

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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