Friday, March 11, 2011

.NET: Remove Empty XML Elements from a XML Document

When you are calling your Oracle Stored procedure using ADO.NET Command object and each of the Parameter is mapped to Dataset’s source column and the XML contains empty elements
You will end up seeing the Exceptions. To avoid this kind of exception the simple way is to Remove empty XML elements from your XML document.
Here is piece of code that saved my life during XML Parsing when creating a Dataset that was mapped to my Façade layer and collaborated with OracleDataAdapter

Protected Function RemoveEmptyXMLElements(ByVal XMLFile As String) As String Dim sXML As String = String.Empty
Try
         Dim XmlDoc As XmlDocument = New XmlDocument      
     XmlDoc.Load(XMLFile)      
     Dim emptyXmlNodeList As XmlNodeList = XmlDoc.SelectNodes("//*[not
                                 (descendant::text()[normalize-space()])]")      
     Dim emptyXmlNode As XmlNode      
    
     For Each emptyXmlNode In emptyXmlNodeList             
         emptyXmlNode.ParentNode.RemoveChild(emptyXmlNode)      
     Next      
     sXML = XmlDoc.InnerXml.ToString()       'XmlDoc.Save(XMLFile)
Catch ex As Exception
   Throw ex
End Try
Return sXML.ToString
End Function

No comments:

Post a Comment