Desidero essere in grado di scrivere XML in una stringa con la dichiarazione e con la codifica UTF-8. Questo sembra molto difficile da realizzare.Forza XDocument per scrivere su String con codifica UTF-8
Ho letto un po 'e ho provato alcune delle risposte popolari per questo, ma hanno tutti problemi. Il mio codice corrente viene emesso correttamente come UTF-8 ma non mantiene la formattazione originale di XDocument (cioè indent/spazio bianco)!
Qualcuno può offrire qualche consiglio per favore?
XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xelementXML);
MemoryStream ms = new MemoryStream();
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
xml.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
String xmlString = sr.ReadToEnd();
}
L'XML richiede la formattazione di essere identico al modo in cui .ToString()
formatterebbe è cioè
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<node>blah</node>
</root>
Quello che sto vedendo è attualmente
<?xml version="1.0" encoding="utf-8" standalone="yes"?><root><node>blah</node></root>
Aggiornamento ho è riuscito a farlo funzionare aggiungendo le impostazioni XmlTextWriter
... Sembra MOLTO goffo !
MemoryStream ms = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
xml.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
String blah = sr.ReadToEnd();
}
Qual 'formattazione'? Non hai detto nulla sulla formattazione! – AakashM
Il solito spazio/formattazione che si ottiene se si giunge a un '.ToString()' su un 'XDocument' o' XElement' – Chris
Fornire un documento di input di esempio in modo da poter verificare le risposte. –