检索xml序列化输出字符串以替换单引号

本文关键字:替换 单引号 字符串 输出 xml 序列化 检索 | 更新日期: 2023-09-27 18:11:38

这就是我序列化对象的方式。我如何检索xml字符串,以取代单引号?

var settings = new XmlWriterSettings {OmitXmlDeclaration = true};
            settings.Encoding = Encoding.ASCII;
            var writer = XmlWriter.Create(writeStream, settings);
            var serializer = new XmlSerializer(value.GetType());
            var nameSpaces = new XmlSerializerNamespaces();
            nameSpaces.Add(string.Empty, string.Empty);
            serializer.Serialize(writer, value, nameSpaces);

检索xml序列化输出字符串以替换单引号

您可以序列化为文本写入器并执行所需的字符串操作,例如:

static void Main(string[] args)
{
    var value = new Class1() { SomeProperty = "content' asdasd' asdasd" };
    var settings = new XmlWriterSettings()
    {
        OmitXmlDeclaration = true,
        Encoding = Encoding.ASCII
    };
    var serializer = new XmlSerializer(typeof(Class1));
    string output = string.Empty;
    var nameSpaces = new XmlSerializerNamespaces();
    nameSpaces.Add(string.Empty, string.Empty);
    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, value, nameSpaces);
        }
        output = textWriter.ToString();
        Console.WriteLine(output);
    }
    string newOutput = output.Replace('''', 'x');
    Console.WriteLine(newOutput);
}

在这个例子中,输出将是

<Class1><SomeProperty>content' asdasd' asdasd</SomeProperty></Class1>
<Class1><SomeProperty>contentx asdasdx asdasd</SomeProperty></Class1>