gpt4 book ai didi

c# - 如何使用 Linq 解析 xml?

转载 作者:太空宇宙 更新时间:2023-11-03 19:29:46 24 4
gpt4 key购买 nike

您好,我有如下所示的 xml 字符串

 <?xml version="1.0" encoding="ISO-8859-1" ?> 
- <Result>
- <AllItems>
- <Item attribute="123">
<SubItem subAttribute="1" />
<SubItem2 subAttribute2="2" />
</Item>
- <Item attribute="321">
<SubItem subAttribute="3" />
<SubItem2 subAttribute2="4" />
</Item>
</AllItems>
</Result>

我想获取 allitems 元素中的每个项目获取属性值并将它们添加到 Enumerable 类

Enumerable<Item> allitems = new Enumerable<Item>();

public class Item()
{
public string attribute{get;set;}
public string subattribute{get;set;}
public string subattribute2{get;set;}
}

如何使用 LINQ 完成?

最佳答案

您的示例在 Linq to XML 中看起来像这样:

XDocument doc = XDocument.Load("test.xml");
var allItems = doc.Descendants("Item").Select(x => new Item()
{
attribute = x.Attribute("attribute").Value,
subattribute = x.Element("SubItem").Attribute("subAttribute").Value,
subattribute2 = x.Element("SubItem2").Attribute("subAttribute2").Value
});

foreach (var item in allItems)
{
Console.WriteLine(string.Format("{0}: {1} / {2} ", item.attribute,
item.subattribute,
item.subattribute2));
}

关于c# - 如何使用 Linq 解析 xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5806782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com