我是一名 C# 开发人员,正在摸索自 VB6 以来编写的第一个 VB 代码,所以如果我问一个相当明显的问题,请原谅我。
我决定尝试使用 XML Literals 来为我生成一些 XML 代码,而不是使用 XMLDocument
我有两个问题,第二个问题是关于解决方法,因为我无法弄清楚第一个问题。
1:理想的解决方案
我有一个 ElementName、ElementValue 的字典,我正在循环遍历其 KeyValue 对,希望动态生成值,但以下语法会死得很惨
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
我对T4语法(<%=%>语法)有模糊的记忆,能够处理更复杂的操作(而不是直接分配给<%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
)2:笨拙的解决方法
相反,我想到构建一个 StringBuilder 对象并将其 .ToString 分配给 XElement,但这也因转换错误而失败。
我更愿意继续在上面的示例 1 中使用我的键值对概念,因为我觉得像上面的示例 2 那样将字符串混在一起相当令人讨厌,如果相反,我真的应该重新使用 XMLDocument。
VB.NET XML Literals 非常强大,但大多数情况下向其中添加一些 LINQ 会使它们真正变得很棒。这段代码应该完全符合您想要做的事情。
Dim Elements = New Dictionary(Of String, String)
Elements.Add("Key1", "Value1")
Elements.Add("Key2", "Value2")
Elements.Add("Key3", "Value3")
Dim xConnections = <Connections>
<%= From elem In Elements _
Select <<%= elem.Key %>><%= elem.Value %></> %>
</Connections>
空的结束标记
</>
是 vb 编译器正确构造 xml 元素所需的全部,该元素的名称是根据 <%= %>
块内的值生成的。
调用 xConnections.ToString 会呈现以下内容:
<Connections>
<Key1>Value1</Key1>
<Key2>Value2</Key2>
<Key3>Value3</Key3>
</Connections>
如果我正确理解你想要做什么,你可以使用 StringBuilder。使用 StringBuilder.Append 方法并附加 XmlElement 'OuterXml' 属性。
例如:
sb.Append(xmlElement.OuterXml)
为了更完整地回答这个问题...
将字符串注入 XML Literal 时,除非在注入 XElement 时使用 XElement.Parse (这是因为特殊字符被转义),否则它将无法正常工作
所以你理想的解决方案更像是这样的:
Dim conns = connections.AsList()
If conns IsNot Nothing AndAlso conns.length > 0 Then
Dim index = 0
Dim xConnections = _
<Connections>
<%= From kvp As KeyValuePair(Of String, String) In conns (System.Threading.Interlocked.Increment(index)).DecompiledElements() _
Select XElement.Parse("<" & <%= kvp.Key %> & ">" & <%= kvp.Value %> & "</" & <%= kvp.Key %> & ">") _
%>
</Connections>
Return xConnections.ToString()
End If
ToString 将正确返回 OuterXML 作为字符串(值不会...) 当然,如果您想返回
的 XElement,只需删除 ToString()由于我不知道 AsList() 的作用,也不知道 DecompiledElements 的作用,因此请相应地设置错误捕获。还有其他方法可以进行循环,这只是一种解决方案。
如果不说动态 XML 元素名称通常是一个坏主意,那我们就太失职了。 XML 的全部要点是以一种易于使用的形式创建存储数据结构:
动态元素名称不符合第一个条件。为什么不简单地使用标准 XML 格式来存储键/值对,如 plists?
<dict>
<key>Author</key>
<string>William Shakespeare</string>
<key>Title</key>
<string>Romeo et</string>
<key>ISBN</key>
<string>?????</string>
</dict>