如何在 Linq 查询中添加输入检查以仅在输入有效时构建 XML
我有一个输入值,需要用它来构建 XML。只有当该值存在时,我才需要构建子元素。
示例
string classInput="something";
XDocument classes = new XDocument(
new XElement("Classes",
new XElement("Class",
new XElement("Name", classInput))
));
返回我想要的内容:
<Classes>
<Class>
<Name>something</Name>
</Class>
</Classes>
但是,上面的查询返回:
<Classes>
<Class>
<Name></Name>
</Class>
</Classes>
在 classInput 为 null 或空的情况下,但我希望它仅在 classInput 是非空字符串时构建子 XML。即在上述情况下,我只想构建:
if, say classInput = "";
尝试在查询中添加检查,但随后它按字符方式处理字符串 classInput,而不是作为字符串。然后我得到
<Classes>
<Class>
<Name>something</Name>
</Class>
</Classes>
更多的输入,我必须以相同的方式构建更多的子元素,所以我需要一个可扩展的解决方案。
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 that can be extensible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用条件运算符检查输入如果输入为 null 或空,则返回 null:
Check the input with a conditional operator and return null if the input is null or empty: