简体   繁体   中英

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

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

<BOOKING partner="CompanyName" transaction="BOOKING" version="1.0">

where CompanyName is a variable. I'm just wondering if anyone can help me add the attributes to the booking element. I am using vb.net do I add the attributes to the class or do I add them during or after serializing? if you could help with code that would be great,

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
    <XmlAttribute>
    Public Property partner As String
    <XmlAttribute>
    Public Property transaction As String
    <XmlAttribute>
    Public Property version As String
End Class

Usage

Dim s = New XmlSerializer(GetType(BOOKING))

If it's a string in code

Dim xml = "<BOOKING partner=""CompanyName"" transaction=""BOOKING"" version=""1.0""/>"

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.

      Dim swLineItem As New IO.StringWriter()
        Dim xmlWriter As New System.Xml.XmlTextWriter(swLineItem)

 xmlWriter.WriteStartDocument()
   xmlWriter.WriteStartElement("YourOuterMostElement")
     xmlWriter.WriteStartElement("Booking") 
       xmlWriter.WriteAttributeString("partner", "CompanyName")
       xmlWriter.WriteAttributeString("transaction", "BOOKING")
       xmlWriter.WriteAttributeString("version", "1.0")

     xmlWriter.WriteEndElement()
    xmlWriter.WriteEndElement()
 xmlWriter.WriteEndDocument() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM