VB.Net/XML LINQ/XAttribute

Материал из VB Эксперт
Перейти к: навигация, поиск

Build an XML element in memory

  
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


FirstName tag"s parent has attributes

  
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


Query elements by attribute value

  
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


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

  
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


Using Linq Xml to query attribute

  

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