使用等效的 streamReader 将 xml 字符串作为参数转换为 class

Converting xml string as parameter to class using streamReader equivalent

我想使用与 read/serialize xml 等效的 StreamReader(不是从文件中检索,而是作为字符串中的参数传递)。

这是我的 class:

public class FH
    {
        public FH();

        public bool AllowD { get; set; }
        public string C_ID { get; set; }
        public string CS_ID { get; set; }
        public FileType FT { get; set; }
        public int G_CK { get; set; }
        public string G_ID { get; set; }
        public bool IsR { get; set; }
        [DefaultValue(-1)]
        public int S_CK { get; set; }
        public string S_ID { get; set; }
    }

这是我的方法:

   public static FH SerializeXMLString (string xmlstring)
            {

            string path = xmlstring;
        FH xmloutput = null;


                    XmlSerializer serializer = new XmlSerializer(typeof(FH));


                    StreamReader reader = new StreamReader(path);


                    xmloutput = (FH)serializer.Deserialize(reader);
                    reader.Close();

                    return xmloutput ;
            }

xml(字符串)为:

<FH>
  <G_ID>XRY</G_ID>
  <G_CK>8</G_CK>
  <CS_ID>RR03</CS_ID>
  <C_ID>YX</CI_ID>
  <AllowD>false</AllowD>
  <S_ID>1888655</S_ID>
  <S_CK>25650</S_CK>
  <FT>
    <ID>55</ID>
    <Name>MI</Name>
    <Purp>Change</Purp>
  </FT>
  <IsR>true</IsR>
</FH>

我意识到 StreamReader 将用于读取文件并需要一个路径,但想知道是否有一个等价物可以用来获取我的 xml 字符串并转换为我的 class (FH) 在返回之前。

非常感谢!

[Serializable]
[XmlType(TypeName = "FH")]
public class FH
{
    public string G_ID{ get; set; }
    public string G_CK{ get; set; }
    public string CS_ID{ get; set; }
    public string C_ID{ get; set; }
    public bool AllowD{ get; set; }
    public string S_ID{ get; set; }
    public string S_CK{ get; set; }
    public FT FT { get; set; }
    public bool IsR{ get; set; }
}


[Serializable]
public class FT
{
    public string ID{ get; set; }
    public string Name{ get; set; }
    public string Purp{ get; set; }
}

首先你应该使用泛型方法。当将 xml 反序列化为另一个 class 时,你会怎么做?你可以看看这个例子。

var response = XmlSampleHelper.SerializeXMLString<FH>(xmlstring, null);

和通用的 SerializeXMLString 方法,

    public static T SerializeXMLString<T>(string xmlstring, string schemaPath)
    {
        var serializer = new XmlSerializer(typeof(T));
        TextReader reader = new StringReader(xmlstring);

        if (!string.IsNullOrWhiteSpace(schemaPath))
            ValidateXmlDocument(reader, schemaPath);

        return (T)serializer.Deserialize(new StringReader(xmlstring));
    }

希望对您有所帮助。