-3

在 C# 中,我如何解析或序列化如下所示的 xml,thanx:

<response>
<result action="proceed" id="19809" status="complete" />
</response>
4

1 回答 1

1

这将满足您的需求:TutorialStackoverflow 正如@LB 所说,在这种情况下,谷歌是您最大的朋友。

其他解决方案:

  1. 为您的 xml 创建一个 xsd 架构。
  2. 使用 xsd.exe 为其创建类。
  3. 使用标准序列化进行序列化。

这是我将我的助手类粘贴到项目中并序列化的时候。

    /// <summary>
/// Serialization helper
/// </summary>
public static class XmlSerializationHelper
{
    /// <summary>
    /// Deserializes an instance of T from the stringXml
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="xmlContents"></param>
    /// <returns></returns>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
    public static T Deserialize<T>(string xmlContents)
    {            
        // Create a serializer
        using (StringReader s = new StringReader(xmlContents))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(s);
        }
    }

    /// <summary>
    /// Serializes the object of type T to the filePath
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="serializableObject"></param>
    /// <param name="filePath"></param>
    public static void Serialize<T>(T serializableObject, string filePath)
    {
        Serialize(serializableObject, filePath, null);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="serializableObject"></param>
    /// <param name="filePath"></param>
    /// <param name="encoding"></param>
    public static void Serialize<T>(T serializableObject, string filePath, Encoding encoding)
    {
        // Create a new file stream
        using (FileStream fs = File.OpenWrite(filePath))
        {
            // Truncate the stream in case it was an existing file
            fs.SetLength(0);

            TextWriter writer; 
            // Create a new writer
            if (encoding != null)
            {
                writer = new StreamWriter(fs, encoding);
            }
            else
            {
                writer = new StreamWriter(fs);
            }   

            // Serialize the object to the writer
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(writer, serializableObject);

            // Create writer
            writer.Close();
        }
    }
}
于 2012-12-06T10:07:18.930 回答