How to change an xml file elements attributes in vb.net

后端 未结 2 840
慢半拍i
慢半拍i 2021-01-28 04:45

Hi I have a class Booking that stores booking information, I have to have BOOKING to look like this



        
2条回答
  •  清歌不尽
    2021-01-28 05:29

    Your class would look like this assuming that's all there is to the node (you didn't close it).

    Imports System.Xml.Serialization
    
    Class BOOKING
        
        Public Property partner As String
        
        Public Property transaction As String
        
        Public Property version As String
    End Class
    

    Usage

    Dim s = New XmlSerializer(GetType(BOOKING))
    

    If it's a string in code

    Dim xml = ""
    

    Or you can read it from a file

    Using sr As New StreamReader("xmlFileNameAndPath.xml")
        xml = sr.ReadToEnd()
    End Using
    

    The deserialize into your BOOKING object

    Dim b As BOOKING = s.Deserialize(New StringReader(xml))
    

    You can then edit the object and serialize it back to the original xml

    b.partner = "different company"
    Using sw As New StreamWriter("xmlFileNameAndPath.xml")
        s.Serialize(sw, b)
    End Using
    

    Though in a real xml file you would have an XmlRoot element (this solution uses BOOKING as the root) then you would be able to have multiple BOOKING elements inside that. Hope this gets you rolling.

提交回复
热议问题