Search code examples
c#xmldocumentxmlnodexmlnodelist

how to identify if a xmlnode has no value?


I want to read an xmlnode and store its values in an array only when they exist.

Here is the xml to be parsed:

 <Signals>
  <Signal_1>
    <SigNum>1</SigNum>
    <SigTypeUni>HIL RPM SYNC OUTPUT </SigTypeUni>
    <SigType>RPM_OUT_0_SENSOR SUPPLY</SigType>
    <HilCnctr>ECU1</HilCnctr>
    <HilCnctrPin>F13</HilCnctrPin>
    <EtasBoard>ESx335_1</EtasBoard>
    <EtasChannel>REF_SG_0</EtasChannel>
    <EtasBobPin>209</EtasBobPin>
    <AddHilIntCnctr />
    <AddPin />
    <LoadNum />
    <LoadRef />
    <LoadRes>400</LoadRes>
    <LoadCard />
  </Signal_1>
  <Signal_2>
    <SigNum>2</SigNum>
    <SigTypeUni>HIL RPM SYNC OUTPUT </SigTypeUni>
    <SigType>RPM_OUT_0_HALL</SigType>
    <HilCnctr>ECU1</HilCnctr>
    <HilCnctrPin>F11</HilCnctrPin>
    <EtasBoard>ESx335_1</EtasBoard>
    <EtasChannel>OUT_SG_0</EtasChannel>
    <EtasBobPin>207</EtasBobPin>
    <AddHilIntCnctr />
    <AddPin />
    <LoadNum />
    <LoadRef />
    <LoadRes />
    <LoadCard />
  </Signal_2>
 </Signals>

I want to extract the value of LoadRes only when it is present.As you can see in second instance the node is present but has no value. I need to ignore such cases. How do I proceed ?

XmlNodeList LoadResNodelist = doc.GetElementsByTagName("LoadRes");     

        foreach (XmlNode node in LoadResNodelist)
        {


            if (node != null) 
            {
                Console.WriteLine(node.InnerXml);
                LoadNum[counterLoadNum] = node.InnerXml;
                counterLoadNum = counterLoadNum + 1;
                Console.WriteLine("counterLoadNum = {0}", counterLoadNum);
            }
}

This is not working out as when the node has no value a blank is printed. How do i focus only on the nodes which have a value?


Solution

  • Just don't loop through them from the first place

     foreach (XmlNode node in LoadResNodelist.Cast<XmlNode>().Where(x=>!string.IsNullOrEmpty(x.InnerXml))