简体   繁体   中英

reading xml file with no value in field vb.net

The following code is giving me fits. I removed the excess baggage and am posting only the relevant parts.

sQuickPath = Server.MapPath("~/App_Data/BillCalculator.xml")
Dim xrXMLReader As XmlReader = XmlReader.Create(sQuickPath)
While xrXMLReader.Read()
    If xrXMLReader.NodeType = XmlNodeType.Element And xrXMLReader.Name = "ServiceType" Then
        Dim ql As XElement = CType(XNode.ReadFrom(xrXMLReader), XElement)
        If IsDBNull(ql.Element("ProposedCustomerCharge").Value) Then
            ProposedCustomerCharge = 0.0
        ElseIf IsNothing(ql.Element("ProposedCustomerCharge").Value) Then 'Check doesn't find empty element
            ProposedCustomerCharge = 0.0
        ElseIf ql.Element("ProposedCustomerCharge").Value Is Nothing Then
            ProposedCustomerCharge = 0.0
        Else
            ProposedCustomerCharge = CType(ql.Element("ProposedCustomerCharge").Value, Double) 'blows chunks
        End If
    End If
End While
xrXMLReader.Close()
xrXMLReader = Nothing

I've tried every way I can think of to zero out the value of ProposedCustomerCharge when that xml field has no value but IsNothing and Is Nothing are not finding the empty field value.

The field in the xml file looks like this:

<ProposedCustomerCharge></ProposedCustomerCharge>

How do I find the empty field?

There were several things wrong here. First; I didn't include enough of the code. The line
Dim ql As XElement = CType(XNode.ReadFrom(xrXMLReader), XElement)
was in the wrong place but you couldn't tell from what I posted. I ended up putting the Dim for ql at the start of the sub and giving it a value inside the loop. I never tried to use it outside the loop but for some reason it was usually set to nothing.

That got me inside the If but still didn't give a match. I added
ElseIf ql.Element("ProposedCustomerCharge").IsEmpty Then ProposedCustomerCharge = 0.0
What I learned from that is that IsEmpty doesn't look for an empty string. If the element exists, empty or not, then it returns false. I finally figured out that what I needed was:
ElseIf ql.Element("ProposedCustomerCharge").Value = "" Then ProposedCustomerCharge = 0.0
That actually matched and set the value of ProposedCustomerCharge to a double value of 0.0.

I also learned that the xml I'm getting doesn't use the best syntax.
<ProposedCustomerCharge></ProposedCustomerCharge> should be <ProposedCustomerCharge />

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