[英]XML serialization, encoding
using System;
public class clsPerson
{
public string FirstName;
public string MI;
public string LastName;
}
class class1
{
static void Main(string[] args)
{
clsPerson p=new clsPerson();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
取自http://support.microsoft.com/kb/815813
1)
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
这条线做什么? 什么是GetType()?
2)如何获得编码
<?xml version="1.0" encoding="utf-8"?>
< clsPerson xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
代替
<?xml version="1.0" encoding="IBM437"?>
<clsPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3
.org/2001/XMLSchema">
或者根本不包括编码类型?
如果您将序列化程序传递给XmlWriter,则可以控制一些参数,如编码,是否省略声明(例如,片段)等。
这并不是一个明确的指南,而是一个替代方案,以便您可以看到正在发生的事情,以及不仅仅是首先要控制的事情。
另请注意,如果使用StringBuilder而不是MemoryStream创建XmlWriter,则xml将忽略您的编码并以utf-16编码形式出现。 有关更多信息,请参阅使用utf8编码编写xml的博客文章。
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = false,
Encoding = Encoding.UTF8
};
using (MemoryStream memoryStream = new MemoryStream() )
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
var x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(xmlWriter, p);
// we just output back to the console for this demo.
memoryStream.Position = 0; // rewind the stream before reading back.
using( StreamReader sr = new StreamReader(memoryStream))
{
Console.WriteLine(sr.ReadToEnd());
} // note memory stream disposed by StreamReaders Dispose()
}
1)GetType()函数返回一个Type对象,表示对象的类型,在本例中为类clsPerson
。 您也可以使用typeof(clsPerson)
并获得相同的结果。 该行为您的特定类创建一个XmlSerializer对象。
2)如果你想改变编码,我相信有一个Serialize()函数的覆盖,你可以指定它。 有关详细信息,请参阅MSDN 您可能必须创建一个XmlWriter对象才能使用它,有关详细信息也在MSDN上 :
XmlWriter writer = XmlWriter.Create(Console.Out, settings);
您还可以在XmlWriter中设置编码,XmlWriterSettings对象具有Encoding属性。
我把@ robert-paulson提供的解决方案带到了我试图做的类似事情并得到了XmlSchema的字符串。 默认情况下,它将返回utf-16。 然而,如上所述,此处的解决方案存在流闭合读取错误。 因此,我利用@Liam提到的tweek移动使用块来自由地将重构作为扩展方法发布。
public static string ToXmlString(this XmlSchema xsd)
{
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = false,
Encoding = Encoding.UTF8
};
using (var memoryStream = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xsd.Write(xmlWriter);
}
memoryStream.Position = 0;
using (var sr = new StreamReader(memoryStream))
{
return sr.ReadToEnd();
}
}
}
1)这为类clsPerson创建了一个XmlSerializer。
2)编码是IBM437,因为这是Console.Out流的形式。
PS:C#中不喜欢匈牙利符号; 只是命名你的班级人物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.