How to add input check in a Linq Query to build XML only if input is valid
I have an input value that I need to use to build out an XML. Only if the value exists, do I need to build the sub-elements.
Example
string classInput="something";
XDocument classes = new XDocument(
new XElement("Classes",
new XElement("Class",
new XElement("Name", classInput))
));
returns what I want:
<Classes>
<Class>
<Name>something</Name>
</Class>
</Classes>
However, the query above returns:
<Classes>
<Class>
<Name></Name>
</Class>
</Classes>
in the case classInput is null or empty, but I want it build the sub-XML only if classInput is a non-empty string. i.e In the above case, I would just like to build out:
<Classes />
if, say classInput = "";
Tried to add a check in the query, but then it processes the string classInput character wise, instead of as a string. Then I get
<Classes>
<Class>
<Name>something</Name>
</Class>
</Classes>
I have some more inputs that I have to build some more sub-elements in the same way, so I need a solution t开发者_运维问答hat can be extensible.
Check the input with a conditional operator and return null if the input is null or empty:
XDocument classes = new XDocument(
new XElement("Classes", String.IsNullOrEmpty(classInput) ?
null :
new XElement("Class",
new XElement("Name", classInput))
));
精彩评论