如何使用 LINQ to XML 检索更深层次的兄弟姐妹?

发布于 2024-11-09 23:50:43 字数 1045 浏览 0 评论 0原文

我的 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>

我尝试了如下但运行时发生异常。

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();

I have an XML structure as follows. I need to extract "Value" and "String" by matching the command attributes? How to write LINQ for this?

 <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>

I tried something as below but exception occurred while running.

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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧伤还要旧人安 2024-11-16 23:50:43

尝试

lst = (
    from command in xmlDoc.Descendants("Info")
    select new EnumList
    {
        val = command.Element("Value").Value,
        stringVal = command.Element("String").Value,
    })
    .ToList();

一下,如果 xml 示例中有错误(没有关闭标签命令),请将其更改为

    </Command>
</Root>

Try

lst = (
    from command in xmlDoc.Descendants("Info")
    select new EnumList
    {
        val = command.Element("Value").Value,
        stringVal = command.Element("String").Value,
    })
    .ToList();

and you have error in xml sample (no close tag Command), change it to

    </Command>
</Root>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文