问题
While building an xml document I require to use logic to dictate the outcome of the xml; logically it is similar to the following piece of code (although this does not work):
Dim buildElement As Boolean = True
Dim xe As XElement = _
<xml>
<% If buildElement Then %>
<BuildMyElement><%= buildElement.ToString %></BuildMyElement>
<% End If %>
</xml>
I have managed to do this using the method show below, is this the suggested way of doing this or is there a better one??
Dim buildElement As Boolean = True
Dim xe As XElement = _
<xml>
<%= If(buildElement, _
<BuildMyElement><%= buildElement.ToString %></BuildMyElement>, _
Nothing) %>
</xml>
回答1:
when you use the If clause in one line you have 2 overload that are:
IF(condition, true, false)
or
If(Condition,False)
You could write something like this to avoid assigning nothing value:
If(buildElement is nothing,<BuildMyElement><%= buildElement.ToString %></BuildMyElement>)
来源:https://stackoverflow.com/questions/5141565/vb-net-linq-to-xml-is-this-the-correct-way-to-use-logic-while-creating-xml