Konwertuj XmlDocument na String
Oto jak obecnie konwertuję XMLDocument na String
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlTextWriter);
return stringWriter.ToString();
Problem z tą metodą polega na tym, że jeśli mam " ((cudzysłowów) które mam w atrybutach) ucieka im
Na Przykład:
<Campaign name="ABC">
</Campaign>
Powyżej jest oczekiwany XML. Ale zwraca
<Campaign name=\"ABC\">
</Campaign>
Mogę zrobić Stringi.Zastąp " \ " ale czy ta metoda jest dobra? Czy są jakieś skutki uboczne? Czy będzie działać dobrze, jeśli sam XML zawiera "\"
5 answers
Nie ma żadnych cytatów. To tylko debugger VS. Spróbuj wydrukować na konsoli lub zapisać do pliku, a zobaczysz. Na marginesie: zawsze pozbywaj się przedmiotów jednorazowego użytku:
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-27 16:44:19
Zakładając, że xmlDoc jest obiektem XmlDocument, co jest złe z xmlDoc.OuterXml?
return xmlDoc.OuterXml;
Właściwość OuterXml zwraca tekstową wersję xml.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-20 12:59:51
Jeśli używasz Windows.Data.Xml.Dom.XmlDocument
wersji XmlDocument
(używanej na przykład w aplikacjach UWP), możesz użyć yourXmlDocument.GetXml()
, aby uzyskać XML jako ciąg znaków.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-01 14:09:07
Jako metoda rozszerzenia:
public static class Extensions
{
public static string AsString(this XmlDocument xmlDoc)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter tx = new XmlTextWriter(sw))
{
xmlDoc.WriteTo(tx);
string strXmlText = sw.ToString();
return strXmlText;
}
}
}
}
Teraz użyj po prostu:
yourXmlDoc.AsString()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-06 22:51:05
"
jest wyświetlany jako \"
w debuggerze, ale dane są poprawne w łańcuchu i nie trzeba niczego zastępować. Spróbuj zrzucić łańcuch do pliku, a zauważysz, że łańcuch jest poprawny.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-02 20:28:13