Reputation: 728
How can we write an XML file into a string variable? Here is the code I have,the variable content is supposed to return an XML string:
public string GetValues2()
{
string content = "";
XmlTextWriter textWriter = new XmlTextWriter(content, null);
textWriter.WriteStartElement("Student");
textWriter.WriteStartElement("r", "RECORD", "urn:record");
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
textWriter.Close();
return contents;
}
Upvotes: 23
Views: 110618
Reputation: 636
You can try:
static string GetXmlString(string strFile)
{
// Load the xml file into XmlDocument object.
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(strFile);
}
catch (XmlException e)
{
Console.WriteLine(e.Message);
}
// Now create StringWriter object to get data from xml document.
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
return sw.ToString();
}
or just use XmlDocument.InnerXml property to get XML string.
XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;
Upvotes: 4
Reputation: 146
HI Pedram You can Try the below code
XmlDocument doc = new XmlDocument();
doc.LoadXml("yourXMLPath");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
sw.ToString();
Upvotes: 2
Reputation: 40970
Something like this
string xmlString = System.IO.File.ReadAllText(fileName);
Here is good answer to create XmlDocument
XDocument or XMLDocument
Upvotes: 71
Reputation: 2449
Try this-
XmlDocument doc = new XmlDocument();
doc.LoadXml(your text string);
StringBuilder sb = new StringBuilder();
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
sb.Append(char.ToUpper(node.Name[0]));
sb.Append(node.Name.Substring(1));
sb.Append(' ');
sb.AppendLine(node.InnerText);
}
return sb;
have a look on this too-
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
and if you really want to create a new XmlDocument then do this
XmlDocument newxmlDoc= myxml
Upvotes: 2