首页 > 解决方案 > 在列表中选择许多 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
                   }));
}

标签: c#xmllinq

解决方案


我认为您的意思是当您注释掉这些元素时会出现异常,因为它们不是文档的一部分。您仅在不引发异常的状态下显示文档。

注释(out),抛出异常:

<!--<video_codec>H264</video_codec>-->

未注释,也不例外:

<video_codec>H264</video_codec>

您需要检查null所有这些Element电话。对属性进行空传播访问 ( ?.)Value是一种简单的方法:

VideoCodec = encoding.Element("video_codec")?.Value

推荐阅读