How to check if an XML node is null?

Asked

Viewed 428 times

1

I have a WS which has a method in which a list of Nodes with some data is inserted. I receive this data as Xmldocument, ride the knot Parameters reading the content inside it, after that I take the data and fill in the parameters of my Procedure to insert into the base.
However there is the possibility of case the data sent via WS is null, the node is not created, and when I try to read the error node.
In which way I can check if the node exists and if not insert NULL in the parameter of Procedure?

Follow the code I’m using to validate this, but it returns error

cmdMailingRetorno.Parameters.AddWithValue(
        "@DataHoraFim",
        Telefones[i]["DataHoraFim"].HasAttributes ?
            (DateTime?)null :
            Convert.ToDateTime(Telefones[i]["DataHoraFim"].InnerText)
);
  • I don’t understand, when the value is null you get null on the Node or it does not exist?

  • @Leandroangelo from what I understand, the knot does not exist in the answer.

  • Rewriting an xml deserializer. That’s exactly what it does. From an object, it feeds the fields that are declared in xml and leaves with the default value those that are not.

  • There is a possibility that if the data sent is null the node is not created!

1 answer

2


Its validation is reversed if Telefones[i]["DataHoraFim"].HasAttributes for true, you are assigning (DateTime?)null as the value of your parameter. You can also check if Node also exists before checking if it has attributes, which also doesn’t make much sense as you are hoping to retrieve the value written inside the node.

Then you need to check if the node exists and if the InnerText is null or has some value.

cmdMailingRetorno.Parameters.AddWithValue(
      "@DataHoraFim",
      (Telefones[i]["DataHoraFim"] == null || !String.IsNullOrEmpty(["DataHoraFim"].InnerText))
      ? null 
      : Convert.ToDateTime(Telefones[i]["DataHoraFim"].InnerText)
);
  • obtained the following error : Sequence was not recognized as valid Datetime,it does not accept as null ?

  • had forgotten to take... you should not pass a DateTime? for the parameter, if it is null is null. Now this error may be in the Telefones[i]["DataHoraFim"].InnerText, it happened in a knot with or without value?

  • Now it worked, buddy, (DateTime?)null otherwise would give conversion error : There is no implicit conversion between "<null> and "Datetime"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.