Search code examples
xmlvb.net

How to set an attribute with a namespace prefix in VB.NET?


I have to use a colon in an XML attribute, but everything before the colon and the colon itself is always being ignored.

That's my source-code:

Dim xmlDoc As New XmlDocument()
Dim rootElement As XmlElement = xmlDoc.CreateElement("export")
rootElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
rootElement.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
xmlDoc.AppendChild(rootElement)
' Kommentare
Dim comment1 As XmlComment = xmlDoc.CreateComment("Kontentabelle")
rootElement.AppendChild(comment1)
Dim comment2 As XmlComment = xmlDoc.CreateComment(DateTime.Now.ToShortDateString())
rootElement.AppendChild(comment2)
Dim comment3 As XmlComment = xmlDoc.CreateComment("**************************************************************************************************************************************")
rootElement.AppendChild(comment3)
'Konten
For Each abs As Account In lst_Absences
    Dim orderElement As XmlElement = xmlDoc.CreateElement("order")
    orderElement.SetAttribute("xsi:type", "ExportAccountListItemExportCalendarAbsence")
    orderElement.SetAttribute("absence", abs.int_AccountNumber.ToString())
    orderElement.SetAttribute("code1", abs.int_AccountNumber.ToString())
    orderElement.SetAttribute("code2", abs.str_AccountName.ToString)
    orderElement.SetAttribute("code3", abs.str_AccountShort.ToString)
    rootElement.AppendChild(orderElement)
Next

In detail, it concerns the 'xsi:type' attribute; however, in the output, only 'type' remains:

<export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <!--Kontentabelle-->
  <!--11.03.2024-->
  <!--**************************************************************************************************************************************-->
  <order type="ExportAccountListItemExportCalendarAbsence" absence="1" code1="1" code2="SampleAbsence" code3="SA" />
</export>

Solution

  • Try this format

    orderElement.SetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance", "ExportAccountListItemExportCalendarAbsence")