Click here to Skip to main content
15,887,822 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear friends,

I am writing a function that creates an xml document named doc which will be consumed by another function. When I write the content of the XML file created (named doc) to a file using

<pre>XmlDocument doc = new XmlDocument();
..........
..........
..........
XmlTextWriter wrtr = new XmlTextWriter("\\doc.xml",Encoding.Unicode);
doc.WriteTo(wrtr);
wrtr.Close();</pre>

it works perfect. But instead of writing the XML document to a file I want to convert its content to string and pass it directly to the consuming function, so I used

<pre> .............
.............
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
doc.WriteTo(xw);
return sw.ToString();</pre>

in this case the output string will contain only 1024 characters (including space) and as a result it will cut some of its contents. What do you suggest to solve it, Thanks!
Posted
Updated 6-Dec-10 5:12am
v4

I think you missed a sw.Flush(); statement.
 
Share this answer
 
Comments
getrelax 2-Nov-10 9:38am    
where should i put sw.Flush(); is that just before the return statement?
use stringbuilder and append xw on per node.. would make sure the data doesnt truncate. can you use alternatives to xml? like json? json is just a string..
 
Share this answer
 
Comments
getrelax 2-Nov-10 8:30am    
Theoretically what you said seems work but suppose we have the following code that create the xml file and writes its content to emp.xml file.

StringBuilder s= new StringBuilder(string.Empty);
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);

XmlElement root = doc.CreateElement("Emp");
doc.AppendChild(root);
XmlElement name = doc.CreateElement("Name");
name.InnerText = "Jhon";
root.AppendChild(name);
XmlElement age = doc.CreateElement("Age");
age.InnerText = "25";
root.AppendChild(age);
XmlTextWriter wrtr = new XmlTextWriter("\\Emp.xml", Encoding.Unicode);
doc.WriteTo(wrtr);
wrtr.Close();

pls show me how i can implement your suggestion and get the content on stringbuilder variable s, Thanks!
[no name] 3-Nov-10 10:30am    
basically if you can read nodes and sh*t like that, u can kinda treat the document like a you would a cursor - add everything that you enter to a stringbuilder using sb.append(string) using the methods mentioned to get the attribute names, node names, etc.
Dalek Dave 6-Dec-10 10:30am    
Hey gerelax, that was Plagiarised from http://www.c-sharpcorner.com/uploadfile/mahesh/readwritexmltutmellli2111282005041517am/readwritexmltutmellli21.aspx

Good try.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900