如何获取以下代码以返回所需的输出。这只是一个主要的简单csharp,没有ASP.NET。
//Desired output: <amp>Before & After</amp>
//instead of
//Current output: <amp>Before & After</amp>
static void Main(string[] args)
{
string amp = "Before & After";
XmlDocument doc = new XmlDocument();
StringBuilder sb = new StringBuilder();
StringWriter stringWriter = new StringWriter(sb);
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.WriteStartElement("amp");
xmlWriter.WriteString(amp);
xmlWriter.WriteEndElement();
global::System.Windows.Forms.MessageBox.Show(sb.ToString());
}
以下是我解决特定问题的方法。
string amp = "Before & After";
XmlDocument doc = new XmlDocument();
StringBuilder sb = new StringBuilder();
StringWriter stringWriter = new StringWriter(sb);
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.WriteStartElement("amp");
xmlWriter.WriteString(amp);
xmlWriter.WriteEndElement();
StringReader valueStringReader = new StringReader(sb.ToString());
XmlTextReader valueXmlReader = new XmlTextReader(valueStringReader);
valueXmlReader.MoveToContent();
global::System.Windows.Forms.MessageBox.Show(valueXmlReader.ReadString());
答案 0 :(得分:2)
如果您想要无效的XML,请自行创建。
string amp = "Before & After";
// don't really do this, it's very wrong
StringBuilder sb = new StringBuilder();
sb.Append("<amp>");
sb.Append(amp);
sb.Append("</amp>");
Console.WriteLine(sb);
但这是 NOT 有效的xml,所以不要这样做。如果要使用XML,则需要使用有效的XML。您的原始代码示例是正确的。
如果你想要更具人性化的东西,那就不要使用XML,使用YAML。
amp: Before & After
答案 1 :(得分:1)
所需的输出不是有效的XML。当前输出与CDATA部分相同,Before & After
和<![CDATA[Before & After]]>
只是两种不同的转义&符号的方式,因此您可以拥有有效的XML。在任何一种情况下,如果您使用任何XML解析器来阅读<amp>
标记的内容,它将返回Before & After
。
答案 2 :(得分:0)
您可以将文字放入CDataSection - 请参阅XmlDocument.CreateCDataSection。
答案 3 :(得分:0)
以下是我解决特定问题的方法。
string amp = "Before & After";
XmlDocument doc = new XmlDocument();
StringBuilder sb = new StringBuilder();
StringWriter stringWriter = new StringWriter(sb);
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.WriteStartElement("amp");
xmlWriter.WriteString(amp);
xmlWriter.WriteEndElement();
StringReader valueStringReader = new StringReader(sb.ToString());
XmlTextReader valueXmlReader = new XmlTextReader(valueStringReader);
valueXmlReader.MoveToContent();
global::System.Windows.Forms.MessageBox.Show(valueXmlReader.ReadString());