Skip to content

Instantly share code, notes, and snippets.

@pisceanfoot
Last active August 29, 2015 14:01
Show Gist options
  • Save pisceanfoot/07945daf91cb83536bc7 to your computer and use it in GitHub Desktop.
Save pisceanfoot/07945daf91cb83536bc7 to your computer and use it in GitHub Desktop.
XmlParser with different xmlroot
public class XmlParser
{
private static Regex regex = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled);
public static T Parse<T>(string body,Encoding encoding) where T : class
{
Type type = typeof(T);
string rootTagName = GetRootElement(body);
XmlAttributes rootAttrs = new XmlAttributes();
rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName);
XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides();
attrOvrs.Add(type, rootAttrs);
XmlSerializer serializer = new XmlSerializer(type, attrOvrs);
object obj = null;
using (System.IO.Stream stream = new MemoryStream(encoding.GetBytes(body)))
{
obj = serializer.Deserialize(stream);
}
return (T)obj;
}
public static T Parse<T>(string body) where T : class
{
return Parse<T>(body, Encoding.UTF8);
}
/// <summary>
/// 获取XML响应的根节点名称
/// </summary>
private static string GetRootElement(string body)
{
Match match = regex.Match(body);
if (match.Success)
{
return match.Groups[1].ToString();
}
else
{
throw new OpenPlatformException("Invalid XML response format!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment