在XML文字中使用字符串

时间:2020-03-05 18:49:44  来源:igfitidea点击:

我是一名Cdeveloper,他正在摸索自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语法(<%=%>语法)的记忆模糊,能够处理更复杂的操作(而不是直接分配给<%=)和类似" Response.Write"的对象,可将输出写入我不记得细节了。

2:笨拙的解决方法

相反,我想到了构建StringBuilder对象并将其.ToString分配给XElement的问题,但这也因转换错误而失败。

我宁愿在上面的示例一中继续使用我的键值对概念,因为我觉得像上面的示例2那样将一个字符串塞在一起很讨厌,如果不是,我真的应该回到使用XMLDocument的角度。

任何想法或者协助,不胜感激

解决方案

回答

如果我正确理解了我们要执行的操作,则可以使用StringBuilder。使用StringBuilder.Append方法并添加XmlElement'OuterXml'属性。

例如:

sb.Append(xmlElement.OuterXml)

回答

我们都会被忽略,更不用说动态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>

回答

VB.NET XML文字功能非常强大,但大多数情况下,向它们添加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元素所需的全部内容是空的结束标记&lt;/>,而xml元素的名称是根据<%=%>块内的值生成的。

调用xConnections.ToString将呈现以下内容:

<Connections>
    <Key1>Value1</Key1>
    <Key2>Value2</Key2>
    <Key3>Value3</Key3>
</Connections>

回答

为了更完整地回答这个问题...

在将字符串注入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的作用,因此请相应地设置错误陷阱。还有其他方法可以执行循环,这只是一种解决方案。