如何参数化 CDATA 部分中的数据

How to parametrize data in a CDATA section

我知道我可以在 vb.net 中像这样向 CDATA 部分添加文本:

Dim temp As System.Xml.Linq.XCData = <![CDATA[Hello World!]]>

但是如何传入一个参数值:

Dim myValue as string = "Hello World!"
Dim temp As System.Xml.Linq.XCData = <![CDATA[myValue]]>

我知道我可以做到,但这是正确的做法吗?

Dim myValue as string = "Hello World!"
Dim temp As New System.Xml.Linq.XCData("<![CDATA[" & myValue & "]]>")

它是这样工作的:

Dim myValue as string = "Hello World!"
Dim temp As System.Xml.Linq.XCData = <![CDATA[<%= myValue %>]]>

供参考:MSDN (How to: Embed Expressions in XML Literals (Visual Basic))

EDIT:所以那是行不通的,因为 CDATA 不允许任何嵌入的表达式。参见:MSDN (XML CDATA Literal (Visual Basic))

所以你剩下XCData的构造函数:

Dim myValue As String = "Hello World!"
Dim temp As New XCData(myValue)

您可以同时使用两者。

Visual Basic 编译器实际上只是将 CDATA 文字转换为

Dim temp = <![CDATA[foo]]>

Dim temp = New XCData("foo")

只需将字符串值提供给 XCData 构造函数,它就会自行放置 CDATA 标签

    Dim myValue As String = "Hello World!"
    Dim temp As New XCData(myValue)