gpt4 book ai didi

c# - XML序列化、编码

转载 作者:可可西里 更新时间:2023-11-01 03:11:34 32 4
gpt4 key购买 nike

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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com