这是我如何序列化一个对象。如何检索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);
答案 0 :(得分:0)
您可以序列化为文本编写器并执行必需的字符串操作,例如:
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>