c# - 在列表中选择许多 XML 节点
问题描述
我需要一些帮助来选择所有<encoding>
节点并将它们添加到List<Core.Encoding>
. 我得到了高度和宽度的值,但是当我取消注释 VideoCodec、AudioCodec 和 ContainerType 时,我得到了错误
对象引用未设置为对象的实例。
有人有想法么?
<media>
<id>123456</id>
<media_type>Video</media_type>
<encodings>
<encoding>
<height>270</height>
<width>404</width>
<video_codec>H264</video_codec>
<audio_codec>Aac</audio_codec>
<container_type>Mp4</container_type>
</encoding>
<encoding>
<height>270</height>
<width>404</width>
<video_codec>H264</video_codec>
<audio_codec>Aac</audio_codec>
<container_type>Mp4</container_type>
</encoding>
</encodings>
</media>
这是我到目前为止所拥有的:
[Serializable]
public class Encoding
{
public string Height { get; set; }
public string Width { get; set; }
public string VideoCodec { get; set; }
public string AudioCodec { get; set; }
public string ContainerType { get; set; }
}
private List<Core.Encoding> SomeMethod(string authenticatedURL)
{
XElement xml = XElement.Load(authenticatedURL);
list.AddRange((from encoding in xml.DescendantsAndSelf("encoding")
select new Core.Encoding
{
Height = encoding.Element("height").Value,
Width = encoding.Element("width").Value,
VideoCodec = encoding.Element("video_codec").Value,
AudioCodec = encoding.Element("audio_codec").Value,
ContainerType = encoding.Element("container_type").Value
}));
}
解决方案
我认为您的意思是当您注释掉这些元素时会出现异常,因为它们不是文档的一部分。您仅在不引发异常的状态下显示文档。
注释(out),抛出异常:
<!--<video_codec>H264</video_codec>-->
未注释,也不例外:
<video_codec>H264</video_codec>
您需要检查null
所有这些Element
电话。对属性进行空传播访问 ( ?.
)Value
是一种简单的方法:
VideoCodec = encoding.Element("video_codec")?.Value
推荐阅读
- php - 我的 URL 的最后一个参数正在拆分(我正在使用 zxing qr 扫描、php 以及前缀和后缀变量)
- flutter - 将 .sqlite db 复制到电话上的文档目录
- c - 如何调用存储在联合中的值
- angular - 在这段代码中结合“mergeMap”和“of”有什么用?
- java - Jenkins 电子邮件配置 - 错误“AuthenticationFailedException”
- scons - Scons PreAction 命令已打印但显然未执行
- sql - PostgreSQL - 显示每个排序组的最后 N 行
- azure - 在 AzureRM 中将 Find-AzureRmResource 替换为 Get-AzureRmResource 以标记资源
- node.js - node.js (i18in) 中的相对 URL
- python - 使用 SciPy/NumPy 循环有限概率权重