如何使用 LINQ 获取 XML 中的子元素值
本文关键字:元素 XML 何使用 LINQ 获取 | 更新日期: 2023-09-27 18:33:59
>我正在尝试访问xml中的子元素值。
<Menus>
<ParentMenu>
<ParentName>Home</ParentName>
</ParentMenu>
<ParentMenu>
<ParentName>Shop</ParentName>
<SubMenus>
<Submenu>
<SubName>SHop1</SubName>
</Submenu>
<Submenu>
<SubName>SHop2</SubName>
</Submenu>
<Submenu>
<SubName>SHop3</SubName>
</Submenu>
<Submenu>
<SubName>SHop4</SubName>
</Submenu>
</SubMenus>
</ParentMenu>
<ParentMenu>
<ParentName>MegaMenu</ParentName>
</ParentMenu>
</Menus>
有我的代码
var menus = (from Parent in xdoc.Root.Descendants("ParentMenu")
select new Menus
{
ParentName = Parent.Descendants("ParentName").First().Value,
Submenus = (from sub in Parent.Descendants("SubMenus")
.Descendants("Submenu")
select new SubMenus
{
SubName = sub.Descendants("SubName")
.First().Value,
}).ToList()
}).ToList();
鉴于您似乎只是将整个 Xml 结构反序列化为 a,我相信 Xml 反序列化是您正在尝试的更好策略:
给定以下 DTO 结构(另请注意ParentMenu
项没有包装器):
public class Submenu
{
public string SubName { get; set; }
}
public class ParentMenu
{
public string ParentName { get; set; }
public List<Submenu> SubMenus { get; set; }
}
public class Menus
{
[XmlElement("ParentMenu")]
public List<ParentMenu> ParentMenus { get; set; }
}
然后你可以简单地反序列化:
var ser = new XmlSerializer(typeof(Menus));
using (var sr = new StringReader(xml)) // Or use TextReader if you are off file
{
var result = (Menus)ser.Deserialize(sr);
}
但是,如果您确实想在 Linq to XML 中手动执行上述反序列化,这将适用于上述相同的 DTO 结构:
var menus = (from Parent in xdoc.Root.Descendants("ParentMenu")
select new ParentMenu
{
ParentName = Parent.Descendants("ParentName").First().Value,
SubMenus = (from sub in Parent.Descendants("SubMenus")
.Descendants("Submenu")
select new Submenu
{
SubName = sub.Descendants("SubName")
.First().Value,
}).ToList()
}).ToList();