简体   繁体   English

如何在vb.net中更改xml文件元素属性

[英]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. 其中CompanyName是变量。 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? 我正在使用vb.net将属性添加到类中还是在序列化期间或之后添加它们? 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 反序列化到您的BOOKING对象中

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

You can then edit the object and serialize it back to the original xml 然后,您可以编辑对象并将其序列化回原始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. 虽然在实际的XML文件中,可以有一个XmlRoot元素(该解决方案采用BOOKING的根),那么你就可以有多个BOOKING中的元素。 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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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