[英]c# List inside list XML Linq
I have the following statement 我有以下声明
xdoc.Descendants("Father").Select(p => new
{
Son1 = (string)p.Element("Son1").Value,
Son2 = (string)p.Element("Son2").Value,
Son3= (string)p.Element("Son3").Value,
Son4 = (string)p.Element("Son4").Value,
Son5 = (string)p.Element("Son5").Value
}).ToList().ForEach(p =>
{
Response.Write("Son1= " + p.Son1 + " ");
Response.Write("Son2=" + p.Son2 + " ");
Response.Write("Son3=" + p.Son3 + " ");
Response.Write(("Son4 =") + p.Son4 + " ");
Response.Write(("Son5 =") + p.Son5 + " ");
Response.Write("<br />");
});
and it works fine as long as i have only one instance of each son , the problem is that i have multiple instances of Son5, and i don´t know how to put Son5 inside of a list 只要我每个儿子只有一个实例,它就可以正常工作,问题是我有多个Son5实例,而且我不知道如何将Son5放入列表中
Here is my XML code Example: 这是我的XML代码示例:
If you have several elements of same type, then you should parse them to list or other collection: 如果您有多个相同类型的元素,则应将它们解析为列表或其他集合:
var fathers = from f in xdoc.Descendants("Father")
select new {
Son1 = (string)f.Element("Son1"),
Son2 = (string)f.Element("Son2"),
Son3= (string)f.Element("Son3"),
Son4 = (string)f.Element("Son4"),
Son5 = f.Elements("Son5").Select(s5 => (string)s5).ToList()
};
Some notes: 一些注意事项:
.Value
of XElement
or XAttribute
- you can cast element itself to appropriate data type without accessing its value. .Value
的XElement
或XAttribute
-你可以施放元素本身对相应的数据类型,而无需访问它的值。 Benefits - less code, more reliable in case element is missing (you will not get NullReferenceException) int
or int?
int
还是int?
as elemenent values if your elements contain integer values Father
element, then don't work with collection of fathers. Father
元素,则不要使用父亲集合。 Just get xml root and check whether it's null or not. father
object. father
对象。 Writing response 写作回应
foreach(var father in fathers)
{
Response.Write($"Son1={father.Son1} ");
Response.Write($"Son2={father.Son2} ");
Response.Write($"Son3={father.Son3} ");
Response.Write($"Son4={father.Son4} ");
Response.Write(String.Join(" ", father.Son5.Select(son5 => $"Son5={son5}"));
Response.Write("<br />");
}
Try this: 尝试这个:
xdoc.Descendants("Father").Select(p => new
{
Son1 = p.Element("Son1").Value,
Son2 = p.Element("Son2").Value,
Son3= p.Element("Son3").Value,
Son4 = p.Element("Son4").Value,
Sons5 = p.Elements("Son5").Select(element => element.Value).ToList()
}).ToList().ForEach(p =>
{
Response.Write("Son1= " + p.Son1 + " ");
Response.Write("Son2=" + p.Son2 + " ");
Response.Write("Son3=" + p.Son3 + " ");
Response.Write("Son4 =" + p.Son4 + " ");
p.Sons5.ForEach(son5 => Response.Write("Son5 =" + son5 + " "));
Response.Write("<br />");
});
That will create a list of Son5
within your list of items, which you can iterate in the ForEach
with another ForEach
. 这将在项目列表中创建一个
Son5
列表,您可以在ForEach
使用另一个ForEach
进行迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.