refactor(work)

This commit is contained in:
Fu Diwei 2021-10-09 16:00:09 +08:00
parent 2bb08b2c02
commit 5ca9a48830
2 changed files with 45 additions and 14 deletions

View File

@ -1,7 +1,5 @@
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Xml.Serialization;
@ -209,18 +207,7 @@ namespace SKIT.FlurlHttpClient.Wechat.Work
try
{
using var stream = new MemoryStream();
using var writer = new System.Xml.XmlTextWriter(stream, Encoding.UTF8);
writer.Formatting = System.Xml.Formatting.None;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(TEvent), new XmlRootAttribute("xml"));
XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(writer, callbackModel, xmlNamespace);
writer.Flush();
xml = Encoding.UTF8.GetString(stream.ToArray());
xml = Regex.Replace(xml, "\\s+<\\w+ (xsi|d2p1):nil=\"true\"[^>]*/>", string.Empty, RegexOptions.IgnoreCase);
xml = Regex.Replace(xml, "<\\?xml[^>]*\\?>", string.Empty, RegexOptions.IgnoreCase);
xml = Utilities.XmlUtility.Serialize(callbackModel);
}
catch (Exception ex)
{

View File

@ -0,0 +1,44 @@
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
namespace SKIT.FlurlHttpClient.Wechat.Work.Utilities
{
internal static class XmlUtility
{
public static string Serialize(Type type, object obj)
{
string xml;
var settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = false;
settings.OmitXmlDeclaration = true;
settings.WriteEndDocumentOnClose = false;
settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
using var stream = new MemoryStream();
using var writer = XmlWriter.Create(stream, settings);
XmlSerializer xmlSerializer = new XmlSerializer(type, new XmlRootAttribute("xml"));
XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(writer, obj, xmlNamespace);
writer.Flush();
xml = Encoding.UTF8.GetString(stream.ToArray());
xml = Regex.Replace(xml, "\\s*<\\w+ (xsi|d2p1):nil=\"true\"[^>]*/>", string.Empty, RegexOptions.IgnoreCase);
xml = Regex.Replace(xml, "<\\?xml[^>]*\\?>", string.Empty, RegexOptions.IgnoreCase);
return xml;
}
public static string Serialize<T>(T obj)
where T : class
{
return Serialize(typeof(T), obj);
}
}
}