LINQ to XML:是否可以进行 XNode 查询
我想在 Silverlight 3 中使用 LINQ to XML,因为没有 XPath 支持。 我已经掌握了窍门。但我正在从事的项目不能保证我将查询的所有 XML 标签都会出现在结果 XML 文件中。
因此,我将无法将整个文件作为 XDocument 进行查询,因为一个文档中缺少标签会使枚举变得混乱。 有没有办法将 XNode 类型转换为 XDocument?我问这个是因为我无法查询 XNode。
I want to use LINQ to XML in Silverlight 3 since there is no XPath support.
I have kind of got the hang of it. But the project I'm working on will not guarantee that all the XML tags I will be querying for will appear in the result XML file.
Due to this I will not be able to query the overall file as XDocument becase the absence of the tag in one document will jumble up the enumeration.
Is there anyway to typecast an XNode to XDocument? I am asking this as I am not able to query the XNode.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使使用 LINQ-to-XML,您也应该按名称进行查询,所以我不确定为什么缺少任何特定标记会“混淆枚举”——简单地说;你可能有一些空值,即
你不能将任意
XNode
转换为XDocument
,但如果你确定它是一个元素,转换为XElement
应该可以满足您的需求。另请注意,当值节点可能丢失时,您可能会发现使用转换运算符最简单:
如果
不存在存在,这将返回一个空的Nullable
- 相同的方法适用于大多数常见的值类型,或者对于仅转换为string
的字符串。Even with LINQ-to-XML you should be querying by name, so I'm not sure why the absence of any particular tag should "jumble up the enumeration" - simply; you might have some nulls, i.e.
You can't cast an arbitrary
XNode
to anXDocument
, but if you are sure it is an element, casting toXElement
should provide what you need.Note also that when value nodes may be missing, you might find it easiest to use the conversion operators:
if
<AuditDate>
doesn't exist, this will return an emptyNullable<DateTime>
- same approach works for most common value-types, or for strings just convert tostring
.