sar*_*rat 2 c# linq linq-to-xml
我有一个XML结构如下.我需要通过匹配命令属性来提取"值"和"字符串"?如何为此编写LINQ?
<Root>
<Command val="1001" type="sync">
<Status>
<DataList>
<Info>
<Value>1</Value>
<String>Sample String 1 is set</String>
</Info>
<Info>
<Value>2</Value>
<String>Sample String 2 is set</String>
</Info>
<Info>
<Value>3</Value>
<String>Sample String 3 is set</String>
</Info>
</DataList>
</Status>
<Command>
</Root>
Run Code Online (Sandbox Code Playgroud)
我尝试了如下所示的东西,但在运行时发生异常.
lst = (
from command in xmlDoc.Descendants("Command")
.Descendants("Status")
.Descendants("DataList")
select new EnumList
{
val = command.Element("Value").Value,
stringVal = command.Element("String").Value,
})
.ToList();
Run Code Online (Sandbox Code Playgroud)
尝试
lst = (
from command in xmlDoc.Descendants("Info")
select new EnumList
{
val = command.Element("Value").Value,
stringVal = command.Element("String").Value,
})
.ToList();
Run Code Online (Sandbox Code Playgroud)
并且您在xml示例中有错误(没有关闭标记命令),将其更改为
</Command>
</Root>
Run Code Online (Sandbox Code Playgroud)