在 XML 文字中使用字符串

发布于 2024-07-04 13:14:21 字数 926 浏览 9 评论 0原文

我是一名 C# 开发人员,正在摸索自 VB6 以来编写的第一个 VB 代码,因此,如果我问的是一个相当明显的问题,请原谅我。

我决定尝试使用 XML Literals 为我生成一些 XML 代码,而不是使用 XMLDocument

我有 2 个问题,第二个问题是关于解决方法,因为我无法弄清楚第一个问题。

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,但这也因转换错误而失败。

我更愿意继续使用上面示例 1 中的键值对概念,因为我觉得像上面示例 2 中那样将字符串混在一起相当令人讨厌,而且我真的应该重新使用 XMLDocument if 相反。

I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.

I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument

I have 2 questions, the second regarding a workaround due to my inability to figure out the first.

1: Ideal solution

I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death

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

I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.

2: Cludgy workaround

Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.

I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

帅的被狗咬 2024-07-11 13:14:21

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

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

To answer this more completely...

When injecting Strings into an XML Literal, it will not work properly unless you use XElement.Parse when injecting an XElement (this is because special characters are escaped)

So your ideal solution is more like this:

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 will return the OuterXML Properly as a String (Value will not...)
of course, just drop the ToString() if you want to return an XElement of

Since I don't know what AsList() does, nor do I know what DecompiledElements do, set your error trapping accordingly. There are other ways to do the loops as well, this is just one solution.

从来不烧饼 2024-07-11 13:14:21

如果不说动态 XML 元素名称通常不是一个好主意,那就太失职了。 XML 的全部要点是以一种易于实现的形式创建存储数据结构:

  1. 可验证、
  2. 可扩展、

动态元素名称不符合第一个条件。 为什么不简单地使用标准 XML 格式来存储键/值对,例如 plist

<dict>
    <key>Author</key>
    <string>William Shakespeare</string>
    <key>Title</key>
    <string>Romeo et</string>
    <key>ISBN</key>
    <string>?????</string>
</dict>

We would all be remiss not to mention that dynamic XML element names are generally a bad idea. The whole point of XML is to create a store a data structure in a form that is readily:

  1. Verifiable
  2. Extendable

Dynamic element names fail that first condition. Why not simply use a standard XML format for storing key/value pairs like plists?

<dict>
    <key>Author</key>
    <string>William Shakespeare</string>
    <key>Title</key>
    <string>Romeo et</string>
    <key>ISBN</key>
    <string>?????</string>
</dict>
话少心凉 2024-07-11 13:14:21

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 元素所需的全部内容,该 xml 元素的名称是根据 <%= %> 中的值生成的。 块。

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

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

VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.

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>

The empty closing tag </> is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a <%= %> block.

Calling xConnections.ToString renders the following:

<Connections>
    <Key1>Value1</Key1>
    <Key2>Value2</Key2>
    <Key3>Value3</Key3>
</Connections>
回忆凄美了谁 2024-07-11 13:14:21

如果我正确理解你想要做什么,你可以使用 StringBuilder。 使用 StringBuilder.Append 方法并附加 XmlElement 'OuterXml' 属性。

例如:

sb.Append(xmlElement.OuterXml)

If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.

For example:

sb.Append(xmlElement.OuterXml)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文