C#:使用没有正确输出的Linq创建XML文档

本文关键字:输出 Linq 创建 文档 XML | 更新日期: 2023-09-27 17:58:01

我正试图从我的数据中创建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>

C#:使用没有正确输出的Linq创建XML文档

要添加到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);

则添加到CCD_ 5。