[英]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? 我正在尝试从我的数据创建xml数据,创建成功,但是输出结果不好,我该如何解决此问题?
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, 要添加到Jon Skeets答案中,
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: xml
是此元素:
XElement xml = new XElement("Navigation",
new XElement("NavigationSets"));
That means xml
is the Navigation
element, not the NavigationSets
element. 这意味着
xml
是Navigation
元素, 而不是 NavigationSets
元素。 I suspect you want something like: 我怀疑您想要类似的东西:
XElement outer = new XElement("Navigation");
XElement inner = new XElement("NavigationSets");
outer.Add(inner);
... then add to inner
. ...然后添加到
inner
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.