2013-04-09 11 views
13

Come possiamo scrivere un file XML in una variabile stringa? Ecco il codice che ho, il contenuto variabile deve restituire una stringa XML:Conversione di un file XML in tipo stringa

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; 

    } 
+0

Quando provo questo il il programma dice che devo definire un percorso invece del contenuto – Pedram

+0

vuoi leggere il file xml nella stringa. ho ragione? – Sachin

+1

Se vuoi creare il file 'xml' e poi assegnarlo a' string' 'variable' usa Linq 2 Xml è il modo più veloce. – harry180

risposta

35

Qualcosa di simile

string xmlString = System.IO.File.ReadAllText(fileName); 

qui è buono risposta a creare XmlDocument XDocument or XMLDocument

+0

Grazie per aver risposto alla mia domanda :) – Pedram

+0

Fammi provare questo – Lijo

1

HI Pedram Puoi provare il codice sottostante

XmlDocument doc = new XmlDocument(); 

doc.LoadXml("yourXMLPath"); 
StringWriter sw = new StringWriter(); 
XmlTextWriter tx = new XmlTextWriter(sw); 
doc.WriteTo(tx); 
sw.ToString(); 
+0

Grazie, ma voglio generare un file XML e salvare in una variabile stringa, non devo caricare o salvare i file in o dal disco rigido – Pedram

1

Prova questo-

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; 

uno sguardo su questo troppo-

StringWriter sw = new StringWriter(); 
    XmlTextWriter tx = new XmlTextWriter(sw); 
    myxml.WriteTo(tx); 

    string str = sw.ToString();// 
    return str; 

e se davvero si vuole creare un nuovo XmlDocument poi fare questo

XmlDocument newxmlDoc= myxml 
Problemi correlati