如何让XmlTextWriter输出的xmlns:cac属性换行显示?
解决XmlTextWriter强制属性单独换行的问题
XmlTextWriter的默认格式化逻辑不会强制单个属性换行,要实现你要的效果,最直接的方案是在两个属性写入之间手动插入换行和对应缩进的空白字符,不用修改现有大量代码,只需要加一行WriteWhitespace调用即可。
修改后的代码:
Dim _xml As New XmlTextWriter(_percorso, System.Text.Encoding.UTF8) _xml.Formatting = Formatting.Indented _xml.Indentation = 7 _xml.NewLine = vbLf ' 可选,指定换行符为LF _xml.WriteStartDocument() _xml.WriteStartElement("DespatchAdvice") _xml.WriteAttributeString("xmlns","urn:oasis:names:specification:ubl:schema:xsd:DespatchAdvice-2") ' 插入换行+缩进,让下一个属性单独占一行 ' 空格数=元素缩进(7) + "<DespatchAdvice "的长度,可根据需求微调对齐效果 _xml.WriteWhitespace(vbLf & Space(7 + 15)) _xml.WriteAttributeString("xmlns:cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2") ' 后续写入逻辑... _xml.WriteEndElement() _xml.WriteEndDocument() _xml.Close()
原理说明:
- XmlTextWriter的
Formatting.Indented仅会对元素内容换行,属性默认会挤在同一行,除非总长度超过内部阈值 - 手动调用
WriteWhitespace写入的空白会被直接保留在输出XML中,不会被格式化逻辑覆盖 - 调整
Space()里的数值可以匹配你想要的缩进对齐效果,确保和第一个属性的缩进一致
为什么之前的尝试无效:
_xml.Settings.NewLineChars:XmlTextWriter没有Settings属性,正确用法是_xml.NewLine,但这仅设置换行符类型,无法强制属性换行- 在属性值后加
& vbLf:XML属性值里的换行符会被自动转义为
,不会变成实际的换行
内容的提问来源于stack exchange,提问作者Luca Geremei
相关产品推荐
相关产品推荐

