c# - Split the String, If it exceeds the specified length -


i generating xml format file using string builder. file :-

  stringbuilder strbldr = new stringbuilder();   strbldr.appendline("<root>");   strbldr.appendline("<productdetails>");   strbldr.appendline("<pid>" + lblproductid.text + "</pid>");   strbldr.appendline("<pdesc>" + strtxtproductdesc + "</pdesc>");   strbldr.appendline("</productdetails>");   strbldr.appendline("</root>"); 

this in loop, may contain many product details. need split string if exceeds limited length suppose 100. till easy. able split using following method:-

 public static ienumerable<string> splitbylength(this string str, int maxlength)  {         (int index = 0; index < str.length; index += maxlength)         {             yield return str.substring(index, math.min(maxlength, str.length - index));         }   } 

but thing is, method splits string if finds length greater 100. need sure if tries split middle of xml node, should find above <productdetails> node , split there. should add code achieve this?

you should use xdocument instead of string construct , query xml data.

you create extension method on xdocument class split length:

public static class xdocumentextensions {     public static ienumerable<string> splitbylength(this xdocument source, string elementname, int maxlength)     {         if (source == null)             throw new argumentnullexception("source");         if (string.isnullorempty(elementname))             throw new argumentexception("elementname cannot null or empty.", "elementname");         if (maxlength <= 0)             throw new argumentexception("maxlength has greater 0.", "maxlength");          return splitbylengthimpl(source, elementname, maxlength);     }      private static ienumerable<string> splitbylengthimpl(xdocument source, string elementname, int maxlength)     {         var builder = new stringbuilder();          foreach (var element in source.root.elements(elementname))         {             var currentelementstring = element.tostring();             if (builder.length + currentelementstring.length > maxlength)             {                 if (builder.length > 0)                 {                     yield return builder.tostring();                     builder.clear();                 }                 else                 {                     throw new argumentexception(                         "source document contains element length greater maxlength", "source");                 }             }              builder.appendline(currentelementstring);         }         if (builder.length > 0)             yield return builder.tostring();     } } 

and use that:

var parts = doc.splitbylength("productdetails", 200).tolist(); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -