VB.NET中如何设置带命名空间前缀的XML属性?
正确设置带命名空间前缀的XML属性(以xsi:type为例)
直接使用SetAttribute("xsi:type", ...)无法保留命名空间前缀,原因是XmlDocument不会自动解析前缀对应的命名空间URI。要解决这个问题,必须使用关联命名空间URI的SetAttribute重载方法。
解决方案
将设置xsi:type属性的代码替换为以下写法:
orderElement.SetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance", "ExportAccountListItemExportCalendarAbsence")
修改后的完整代码
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") ' 使用带命名空间URI的SetAttribute重载设置xsi:type orderElement.SetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance", "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
正确输出结果
<export xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <!--Kontentabelle--> <!--11.03.2024--> <!--**************************************************************************************************************************************--> <order xsi:type="ExportAccountListItemExportCalendarAbsence" absence="1" code1="1" code2="SampleAbsence" code3="SA" /> </export>
原理说明
XML中的命名空间前缀(如xsi)是对应URI的别名,XmlDocument需要明确属性关联的命名空间URI才能正确生成带前缀的属性。上述重载方法通过指定:
- 属性的本地名称(
type) - 命名空间URI(
http://www.w3.org/2001/XMLSchema-instance,对应前缀xsi) - 属性值
让文档正确绑定前缀与命名空间,输出符合预期的XML结构。
内容的提问来源于stack exchange,提问作者Flodsche
相关产品推荐
相关产品推荐

