Saturday, July 6, 2013

Remove All Empty Tags From XML in Java , C#




To Day I will Show you how to Remove All Empty Tags from XML File or a string Variables containing   XML Data in both C# and Java.
In My Previous tutorial  i show After Removing Empty Tags from XML there will be Empty Line in XML beside these tags.So you Must through this Tutorial as well.
In this tutorial Again i Use Reg-ex Expression  To Detect or Find empty tags from XML string or File and  replace there my respected tags or String and left them empty.
Lets Start,
Suppose We have XML file or String variable having XML data.
<ssn>111111111</ssn>
<employment>
<current>
<address>
<line1>
<line2>
<line3>
<city>
<state>
<country>
</country></state></city></line3></line2></line1></address>
<phone>
<phonenumber>
<countrycode>
</countrycode></phonenumber></phone>
</current>
<previous>
<address>
<line1>
<line2>
<line3>
<city>
<state>
<country>
</country></state></city></line3></line2></line1></address>
<phone>
<phonenumber>
<countrycode>
</countrycode></phonenumber></phone>
</previous>
</employment>
<maritalstatus>Single</maritalstatus>



Lets we have String Variable Name "xml" Contains above xml File data
String xml = //get the XML
xml = xml.replaceAll("<.*?/>", "");



This will remove empty tags like
"<city/>" but not "<Address></Address>".
For this changee above line With below Line
xml = xml.replaceAll("<.*?></.*?>", "");

OUT PUT WILL BE:-
<SSN>111111111</SSN>
<MaritalStatus>SINGLE</MaritalStatus>



- Full Post

No comments:

Post a Comment