7

いくつかの単純なプロパティを持つProfileというクラスがあり、次にいくつかの単純なプロパティを持つProfileItemのコレクションを持つことができ、次にProfileItem (RECURSION)のコレクションを持つことができます。

現在、VB.NET (3.5) に付属の XML リテラルを使用して、非常に単純な保存関数を生成しようとしています。

私が使用しているコードは次のとおりです。

  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>

タグに関する部分は再帰的になるはずですが、この構文で何らかの形でサポートされているかどうかはわかりません。

再帰を実装するために XML リテラルの使用を避けてすべて書き直す必要がありますか?

4

1 に答える 1

9

再帰は、私がVB.NETXMLリテラルを愛する理由の1つです。

再帰を実行するには、ProfileItemsコレクションを受け入れてXElementを返す関数が必要です。次に、XMLLiteral内でその関数を再帰的に呼び出すことができます。

また、再帰が機能するためには、GetProfileItemsとGetDependenciesが同じ名前(そのうちの1つに名前を変更)を持ち、同じ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要素は空になります:<items/>itemsXMLリテラルは、子要素がない場合に開始タグと終了タグを組み合わせるのに十分スマートです。

于 2009-07-28T18:00:03.553 に答える