【问题标题】:Recursion with XML Literals in VB.NET is possible?可以在 VB.NET 中使用 XML Literals 进行递归吗?
【发布时间】:2010-11-14 16:09:53
【问题描述】:

我有一个名为 Profile 的类,它有一些简单的属性,然后它可以有一个 ProfileItem 的集合,它又具有一些简单的属性,然后它可以有一个集合ProfileItem(递归)。

现在我正在尝试使用 VB.NET (3.5) 附带的 XML Literals 生成一个非常简单的保存函数。

我使用的代码如下:

  Dim xdoc As XDocument = _
            <?xml version="1.0" encoding="utf-8"?>
            <profiles>
                <%= _
                    From p In _Profiles _
                    Select <profile name=<%= p.Name %>>
                               <%= _
                                   From i In p.GetProfileItems _
                                   Select <item>
                                              <name><%= i.Name %></name>
                                              <action><%= i.Action.ToString %></action>
                                              <type><%= i.Type.ToString %></type>
                                              <arguments><%= i.Arguments %></arguments>
                                              <dependencies>
                                                  <%= _
                                                      From d In i.GetDependencies _
                                                      Select <dependency>
                                                                 <name><%= d.Name %></name>
                                                             </dependency> _
                                                  %>
                                              </dependencies>
                                          </item> _
                               %>
                           </profile> _
                %>
            </profiles>

tag相关的部分应该是递归的,不知道这个语法有没有某种方式支持。

我应该重写所有避免使用 XML Literal 来实现递归吗?

【问题讨论】:

  • 哇,因为 C# xml 文字看起来或感觉都不对。

标签: vb.net .net-3.5 recursion xml-literals


【解决方案1】:

递归是我喜欢 VB.NET XML Literals 的原因之一!

为了进行递归,您需要一个接受 ProfileItems 集合并返回 XElement 的函数。然后,您可以在 XML Literal 中递归调用该函数。

此外,为了使递归起作用,GetProfileItems 和 GetDependencies 需要具有相同的名称(重命名其中之一)并以相同的 Xml 元素结构显示。下面是递归函数的样子:

Function GetProfileItemsElement(ByVal Items As List(Of ProfileItem) As XElement
    Return <items>
               <%= From i In Items _
                   Select <item>
                              <name><%= i.Name %></name>
                              <!-- other elements here -->
                              <%= GetProfileItemsElement(i.GetDependencies) %>
                          </item> %>
           </items>
End Function

当您到达一个为 GetDependencies 函数返回一个空列表的项目时,递归将结束。在这种情况下,嵌套的items 元素将为空:&lt;items/&gt;。 XML 文字足够聪明,可以在没有任何子元素时组合开始和结束 items 标记。

【讨论】:

  • 伟大的丹尼斯,你的回答对我帮助很大
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 2021-03-28
  • 2019-04-18
相关资源
最近更新 更多