c# - XML序列化、编码

标签 c# asp.net xml web-services xml-serialization

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 编码输出。请参阅博文 writing xml with utf8 encoding获取更多信息。

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()
}

关于c# - XML序列化、编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4928323/

相关文章:

asp.net - 通过wcf服务通过邮寄方式消费表单数据

javascript - 使用 Jquery 在 asp.net GridView 中查找所有复选框

c# - 检查注入(inject)参数中的空值是否有意义?

android - 无法使 roughike 底部栏导航标题居中

c# - 如何使用 C# 打开谷歌浏览器窗口(仅页面)

c# - 字符串比较问题

C# 网络 API 调用

c# - IdentityRole 上缺少类型映射配置或不受支持的映射

c# - Xaml 中的 XPath 选择节点

xml - 如何强制子元素在 XSD 中具有值?