Question

Je peuplant un objet anonyme à partir d'un fichier XML. Jusqu'à présent,

commentary.Elements("Commentator")

a toujours eu une valeur, donc je ne l'ai jamais dû vérifier null. J'ai dû enlever que si, et maintenant il est défaillant quand il essaie de lire cette ligne.

Je regarde le code et je ne sais pas quoi changer cependant, parce que son être sélectionné dans une propriété d'un objet anonyme.

var genericOfflineFactsheet = new
    {
        Commentary = (from commentary in doc.Elements("Commentary")
                      select new
                      {
                          CommentaryPage = (string)commentary.Attribute("page"),
                          BusinessName = (string)commentary.Attribute("businessName"),
                          Commentator = (from commentator in commentary.Elements("Commentator")
                                         select new CommentatorPanel // ASP.NET UserControl
                                         {
                                             CommentatorName = (string)commentator.Attribute("name"),
                                             CommentatorTitle = (string)commentator.Attribute("title"),
                                             CommentatorCompany = (string)commentator.Attribute("company")
                                         }).FirstOrDefault()
                      }).FirstOrDefault()

La chose est, je ne peux pas supprimer complètement la ligne parce que parfois commentary.Elements("Commentator") ne ont une valeur. Je suis sûr que cette question a été traitée, mais je ne vois pas ce qu'il faut faire. Toutes les idées?

Était-ce utile?

La solution

Il suffit d'ajouter un chèque nul. (Code ci-dessous devrait être un bon testeur. A un avec et un sans Commentateur)

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("Example"),
new XElement("Commentarys",
        new XElement("Commentary",
            new XAttribute("page", "2"),
            new XAttribute("businessName", "name"),
            new XElement("Commentator",
               new XAttribute("name", "name"),
                new XAttribute("title", "title")
            )
         )
        ,
        new XElement("Commentary",
            new XAttribute("page", "3"),
            new XAttribute("businessName", "name2")

            )
    )
    );
var genericOfflineFactsheet = new
{
    Commentary = (
           from commentary in doc.Elements()
                .First().Elements("Commentary")
           select new
          {
              CommentaryPage = (string)commentary.Attribute("page"),
              BusinessName = (string)commentary.Attribute("businessName"),
              Commentator = (from commentator in commentary.Elements("Commentator")
                             where commentator != null //<-----you need to add this line
                             select new // ASP.NET UserControl
                             {
                                 CommentatorName = (string)commentator.Attribute("name"),
                                 CommentatorTitle = (string)commentator.Attribute("title"),
                                 CommentatorCompany = (string)commentator.Attribute("company")
                             }

                             ).FirstOrDefault()
          }
 ).FirstOrDefault()
};

Autres conseils

... Untested

Que diriez-vous quelque chose comme:

  XElement xe = doc.Elements("Commentary").FirstOrDefault();
  Commentary = xe == null ? null :
    select new { ....snip....

Ceci est un cas où je pourrais considérer la ?? (Coalesce) de l'opérateur .

null ?? x --> x

Dans ce cas, vous pourriez vous en sortir avec un coalescent Enumerable vide.

J'utilise le? opérateur ainsi pour éviter un xmlelement à générer:

  • si l'utilisation objet I est non nul, je reviens un nouveau XElement dans un tableau
  • si elle est nulle, je retourne un Enumerable.Empty

Exemple:

var xml = new XElement("Root",
    myobject == null ? Enumerable.Empty<XElement>() : <= empty IEnumerable if it is null
                       new []                         <= a array with a XElement
                           { 
                               new XElement("myobject", 
                                   new XAttribute("Name", myobject.Name),
                                   new XAttribute("Type", myobject.Type)
                               ...)
                           },
    ...);

Dans ce cas, le XElement ne sera pas générée si l'objet impliqué dans sa création est nulle.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top