c#序列化,我只得到根接近字符串

本文关键字:接近 字符串 序列化 | 更新日期: 2023-09-27 18:13:19

我想将一个类序列化为字符串。我使用以下代码将其序列化为string:

root root = new root();
rootHeader header = new rootHeader() { 
   SystemName = "pontaz", 
   SystemVersion = 1, 
   SessionId = 1, 
   CommandName = "Connect", 
   ConnectOption = 0 
};
// get it to xml and to string
XmlWriterSettings settings = new XmlWriterSettings();
settings.NewLineHandling = NewLineHandling.Entitize;
settings.Indent = false;
StringWriter StringWriter = new StringWriter();
XmlWriter writer = XmlWriter.Create(StringWriter,settings);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XmlSerializer MySerializer = new XmlSerializer(typeof(root));
MySerializer.Serialize(writer, root, namespaces);
string s = StringWriter.ToString();

当它运行时,我返回:

<?xml version="1.0" encoding="utf-16"?><root />

,但应该是:

<?xml version="1.0" encoding="utf-8"?>
<root>
   <Header>
      <SystemName>OTHERSYSTEM</SystemName>  
      <SystemVersion>1.00</SystemVersion><SessionId>1</SessionId> 
      <CommandName>Connect</CommandName>  
      <ConnectOption>0</ConnectOption>  
   </Header>
</root>

我错过了什么吗?

c#序列化,我只得到根接近字符串

添加rootHeaderroot

首先,您需要确保在创建新的元素和rootHeader之后,将rootHeader添加到元素:
root root = new root();
rootHeader header = new rootHeader() { 
   SystemName = "pontaz", 
   SystemVersion = 1, 
   SessionId = 1, 
   CommandName = "Connect", 
   ConnectOption = 0 
};
// add rootHeader to root element somewhere here
// before serializing it...

root元素可以将rootHeader标记为xmlatattribute

静态/私有字段序列化

您说您在代码中将rootHeader添加到,请确保不是将其添加为静态字段,并且是公共

要序列化的所有字段必须是公共的,而不是静态的。

。Net序列化序列化实例;静态字段不属于到一个实例。

这是所有我可以建议你尝试从你提供的代码和信息。

我不知道你在哪里添加rootHeader到root ..

您可以使用XmlSerializer内置类来简化您的工作,该类还将输出写入文件

// Namespace containing the serialization class
using System.Xml.Serialization;
// instances the serializer and tells wich type it will serialize
XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));
 // Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(@"C:'output.xml");
// Serialize and write on file
SerializerObj.Serialize(WriteFileStream, TestObj);
// Close stream writer
WriteFileStream.Close();