2014-03-29 25 views
2

我在vb中使用了xml文字。我想插入一個變量(在運行時派生)到註釋中,比如類似的;如何將變量插入到xml文字註釋

Dim vtldMessageBoxes = 
      <?xml version="1.0" encoding="UTF-8"?> 
      <!--Information about messageboxes. Do not delete this file unless <%= My.Application.Info.Title %> has been deleted. --> 
       <Users> 
        <username><%= Environment.UserName %> 
        </username> 
       </Users> 

如果我運行此代碼,則應用程序標題不會出現在註釋中。簡單的問題是,是否可以在運行時在xml文字註釋中嵌入變量,如果是這樣的話?

謝謝

回答

3

你絕對是對的,你不能在XML文字的註釋中嵌入表達式。這是因爲用於表達式的轉義字符是有效的註釋字符。該XML comment literal documentation明確要求這一點:

在XML註釋不能使用嵌入式表達式字面 因爲嵌入式表達式分隔符是有效的XML註釋 內容。

要解決這個問題,你只需要註釋添加到由XML文本創建的XDocument

Dim vtldMessageBoxes = 
    <?xml version="1.0" encoding="UTF-8"?> 
    <Users> 
     <username><%= Environment.UserName %> 
     </username> 
    </Users> 

Dim fullComment = String.Format("Information about messageboxes. Do not delete this file unless {0} has been deleted.", My.Application.Info.Title) 

vtldMessageBoxes.AddFirst(New XComment(fullComment)) 
MessageBox.Show(vtldMessageBoxes.ToString()) 
+0

輝煌的解釋,謝謝約翰。 –

相關問題