XLINQ:xml 中缺少元素
我有以下 xml
<students>
<student>
<id>12</id>
<name>Mohsan</name>
</student>
<student>
<id>2</id>
</student>
<student>
<id>3</id>
<name>Azhar</name>
</student>
</students>
注释,其中缺少 2 个名称元素。
我必须使用 Linq to XML 读取此 xml
我使用以下代码来获取所有学生..
请建议我改进此代码
var stds = from std in doc.Descendants("student")
select new
{
ID = std.Element("id").Value,
Name = (std.Element("name")!=null)?std.Element("name").Value:string.Empty
};
i have the following xml
<students>
<student>
<id>12</id>
<name>Mohsan</name>
</student>
<student>
<id>2</id>
</student>
<student>
<id>3</id>
<name>Azhar</name>
</student>
</students>
note that in 2 name element is missing.
i have to read this xml using Linq to XML
i used following code to get all students..
please suggest me improvement in this code
var stds = from std in doc.Descendants("student")
select new
{
ID = std.Element("id").Value,
Name = (std.Element("name")!=null)?std.Element("name").Value:string.Empty
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以利用以下事实:存在 来自
XElement
的显式转换到string
,对于 nullXElement
引用返回 null。然后,您可以使用 null 合并运算符从 null 变为空字符串:You can use the fact that there's an explicit conversion from
XElement
tostring
, which returns null for a nullXElement
reference. You can then use the null-coalescing operator to go from null to an empty string:使用“let”的语法可以避免两次询问 Element("name")
Syntax with 'let' allows you avoid twice ask Element("name")
这有点晚了,但可能会帮助其他人解决这个问题。我有一个相当大的对象,有 90 个属性,我试图从 XML 文件中转换成这些属性,因此为了让事情变得更容易,我创建了一些方法。
然后就很容易使用了,如下所示:
This is a little late, but may help someone else looking through this. I had a rather large object with 90 properties I was trying to cast into from an XML file, so to make things easier I created a few methods.
Then it was pretty easy to use like this: