VB.Net/XML LINQ/XAttribute

Материал из VB Эксперт
Версия от 15:45, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Build an XML element in memory

<source lang="vbnet"> Class Car

 Public PetName As String
 Public ID As Integer

End Class Module Program

 Sub Main()
   Dim inventory As XElement = _
     New XElement("Inventory", _
       New XElement("Car", New XAttribute("ID", "1"), _
         New XElement("Color", "Green"), _
         New XElement("Make", "BMW"), _
         New XElement("PetName", "Stan") _
       ) _
     )
   Console.WriteLine(inventory)
 End Sub

End Module


 </source>


FirstName tag"s parent has attributes

<source lang="vbnet"> Imports System Imports System.Reflection Imports System.Xml Module Module1

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("FirstName tag"s parent has attributes: {0}", firstName.Parent.HasAttributes)
   End Sub

End Module


 </source>


Query elements by attribute value

<source lang="vbnet"> Imports System Imports System.Reflection Imports System.Xml Module Module1

   Sub Main()
       Dim xml As XDocument = XDocument.Load("People.xml")
       Dim query = From p In xml.Elements("people").Elements("person") _
           Where p.Element("id").Value = 1 _
           Select p
       For Each record In query
           Console.WriteLine("Person: {0} {1}", _
              record.Element("firstname").Value, _
              record.Element("lastname").Value)
       Next
   End Sub

End Module


 </source>


The element axis property (<>) and the attribute axis property (@) are used to access the id attribute.

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim maxId As Integer = Aggregate ele In employees.<Employee> Into Max(CInt(ele.@id))
           Dim newEmployee = <Employee id=<%= maxId + 1 %>>
                                 <Name>First</Name>
                                 <Title>Coder</Title>
                                 <HireDate>07/15/2006</HireDate>
                                 <HourlyRate>9.95</HourlyRate>
                             </Employee>
           employees.Add(newEmployee)
       End Sub
   End Class
  
   
 </source>


Using Linq Xml to query attribute

<source lang="vbnet">

Module Program

 Sub Main()
   Dim doc As XElement = XElement.Load("Inventory.xml")
   Dim ids = From c In doc.<Car> Select c.@carID
   For Each id In ids
     Console.WriteLine(id)
   Next
 End Sub

End Module


 </source>