简体   繁体   中英

Check for missing int value xml element

In my C# program, I'm loading car data from an xml file into car objects.

This is my xml file:

  <Car>
    <CarID>1</CarID>
    <CarName>Honda</CarName>
    <CarColor>Blue</CarColor>
  </Car>
  <Car>
    <CarName>Ford</CarName>
    <CarColor>Yellow</CarColor>
  </Car>
  <Car>
    <CarID>3</CarID>
    <CarName>BMW</CarName>
    <CarColor>Green</CarColor>
  </Car>

NOTE THAT the second car entry does NOT have an ID. So I would need to check for this to avoid a null exception.

I load the xml data in my C# code like this:

      List<Car> Cars =
(
    from el in XDocument.Load("XML_Files/cars.xml").Root.Elements("Car")
    select new Car
    {
        CarID = (int)el.Element("CarID"),
        CarName = (string)el.Element("CarName"),
        CarColor = (string)el.Element("CarColor")
    }).ToList();

I've read in another question that to get around this, for string data, we replace this:

CarName = (string)el.Element("CarName")

with this:

CarName = ((string)el.Element("CarName") != null) ? (string)el.Element("CarName") : string.Empty

That works fine for string values, but what I cannot figure out is how to apply this logic for int values.

So how do I modify this line:

CarID = (int)el.Element("CarID")

To test for the null value?

I've tried this way, but it does not work:

CarID = ((int)el.Element("CarID") >= 0) ? Convert.ToInt32(el.Element("CarID").Value) : 0

Any suggestions?

You're doing two fundamentally different checks in your two examples. In the string example, you're checking if the element is null . In the int example, you're assuming that it exists and jump straight to checking the integer value. Check first that it's not null like you do with the string example.

CarID = (el.Element("CarID") != null) ? Convert.ToInt32(el.Element("CarID").Value) : 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM