在同一个LinqToXml查询中写下联系人的电话?

时间:2011-11-11 14:27:13

标签: linq-to-xml

我有这个代码。

   Dim contact1 As XElement = _
        <contacts>
            <contact>
                <%= From contact In contacts _
                    Select <name><%= contact.Nom %></name> %>
            </contact>
        </contacts>

此代码实际上选择了联系人

有2个物体,联系人和电话。联系人可以保存电话号码列表。课程详情......

Public Class Contact

    Private m_Name As String
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set(ByVal value As String)
            m_Name = value
        End Set
    End Property

    Private m_Phones As List(Of Phone)
    Public Property Phones() As List(Of Phone)
        Get
            Return m_Phones
        End Get
        Set(ByVal value As List(Of Phone))
            m_Phones = value
        End Set
    End Property

End Class

Public Class Phone

    Private m_Contact As Contact
    Public Property Contact() As Contact
        Get
            Return m_Contact
        End Get
        Set(ByVal value As Contact)
            m_Contact = value
        End Set
    End Property

    Private m_Number As String
    Public Property Number() As String
        Get
            Return m_Number
        End Get
        Set(ByVal value As String)
            m_Number = value
        End Set
    End Property

End Class

如何在此查询中为每个<phone type="...">...</phone>中的手机添加手机?

奖金(+1):如何包含该类型?

感谢。

1 个答案:

答案 0 :(得分:0)

您还没有清楚地描述您想要的结果或问题所在,可能以下代码示例有帮助:

Dim contact1 As New Contact() With {
    .Name = "John Doe",
    .Phones = New List(Of Phone) From {New Phone() With {.Number = "555 12345"}, New Phone() With {.Number = "123 54321"}}
}
Dim contacts As New List(Of Contact)() From {contact1}
Dim contactElements As XElement = _
     <contacts>
         <%= From contact In contacts
             Select <contact>
                        <name><%= contact.Name %></name>
                        <phones>
                            <%= From phone In contact.Phones
                                Select <phone><%= phone.Number %></phone>
                            %>
                        </phones>
                    </contact>
         %>
     </contacts>

输出

<contacts>
  <contact>
    <name>John Doe</name>
    <phones>
      <phone>555 12345</phone>
      <phone>123 54321</phone>
    </phones>
  </contact>
</contacts>