xml去除头部

/// <summary>
/// 去除头部xml头
/// </summary>
public class XmlMessageSerializer
{
public static string SerializeToXML(Object obj)
{
string outXML = string.Empty;
if (obj == null)
return outXML;
XmlSerializer xs = new XmlSerializer(obj.GetType(),
new XmlRootAttribute("input"));
//namsepaces is emty
//to remove xmlns <xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, string.Empty) // Default Namespace
});
// I'll use a MemoryStream as my backing store.
using (MemoryStream ms = new MemoryStream())
{
// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
//equal writer.Formatting = Formatting.Indented;
xws.Indent = true;
var xwr = XmlTextWriter.Create(ms, xws);
// remove <?xml header
//http://stackoverflow.com/questions/7913798/xmlserializer-to-xelement
ms.Position = 0;
xs.Serialize(xwr, obj, namespaces);

outXML = System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
return outXML;
}
public T DeSeriralze<T>(string xmlStr)
{
XmlSerializer xmS = new XmlSerializer(typeof(T));
object recoveryObject = null;
StringReader sr = null;
try
{
sr = new StringReader(xmlStr);
//默认用UTF-8打开文件
recoveryObject = xmS.Deserialize(sr);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (sr != null)
sr.Close();
}
return (T)recoveryObject;
}
}

posted @ 2022-04-05 20:07  .net&new  阅读(430)  评论(0编辑  收藏  举报