使用沼泽标准的System.Xml.Serialization.XmlSerializer,我可以序列化一个对象,该对象的类从另一个继承。检查生成的XML,为根节点赋予属性“ p1:type”和“ xmlns:p1”:
<ApiSubmission ApiVersion="1" CustId="100104" p1:type="OrderConfirmationApiSubmission"
xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">
...
</ApiSubmission>
有没有删除这些属性的好方法?
因此,在最初提出这个问题的5年后,我遇到了同样的问题,对于没有人回答我感到失望。搜索后,我将一些东西拼凑在一起,这使我可以删除派生类中的type属性。
internal static string SerializeObject(object objectToSerialize, bool OmitXmlDeclaration = true, System.Type type = null, bool OmitType = false, bool RemoveAllNamespaces = true)
{
XmlSerializer x;
string output;
if (type != null)
{
x = new XmlSerializer(type);
}
else
{
x = new XmlSerializer(objectToSerialize.GetType());
}
XmlWriterSettings settings = new XmlWriterSettings() { Indent = false, OmitXmlDeclaration = OmitXmlDeclaration, NamespaceHandling = NamespaceHandling.OmitDuplicates };
using (StringWriter swriter = new StringWriter())
using (XmlWriter xmlwriter = XmlWriter.Create(swriter, settings))
{
x.Serialize(xmlwriter, objectToSerialize);
output = swriter.ToString();
}
if (RemoveAllNamespaces || OmitType)
{
XDocument doc = XDocument.Parse(output);
if (RemoveAllNamespaces)
{
foreach (var element in doc.Root.DescendantsAndSelf())
{
element.Name = element.Name.LocalName;
element.ReplaceAttributes(GetAttributesWithoutNamespace(element));
}
}
if (OmitType)
{
foreach (var node in doc.Descendants().Where(e => e.Attribute("type") != null))
{
node.Attribute("type").Remove();
}
}
output = doc.ToString();
}
return output;
}
我使用这个,并在基类中使用[XmlInclude]派生类。然后是OmitType和RemoveAllNamespaces。从本质上讲,然后将派生类视为基类。
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다