Last active
August 29, 2015 14:01
-
-
Save pisceanfoot/07945daf91cb83536bc7 to your computer and use it in GitHub Desktop.
XmlParser with different xmlroot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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