XmlSerializer忽略的类属性

时间:2018-03-16 09:53:33

标签: c# xml xmlserializer

我有一个代表书的类,当我运行SerializeToXmlElement()方法时,它包含类,但不包括类属性。如何确保公共属性包含在XML输出中?

预订课程

[XmlType("Edition")]
public class Book 
{
    #region Attributes
    private string series;
    private string title;
    private string isbn;
    private string pubDate;
    #endregion Attributes

    #region Encapsulated fields
    [XmlElement]
    public string Series { get => series; set => series = value; }
    [XmlElement]
    public string Title { get => title; set => title = value; }
    [XmlElement("ISBN")]
    public string Isbn { get => isbn; set => isbn = value; }
    [XmlElement("Publication_Date")]
    public string EditionPubDate { get => pubDate; set => pubDate = value; }
    #endregion Encapsulated fields

    #region Constructors
    public Book() { }
    #endregion Constructors

    #region Methods
    public XmlElement SerializeToXmlElement()
    {
        XmlDocument doc = new XmlDocument();
        using (XmlWriter writer = doc.CreateNavigator().AppendChild())
        {
            new XmlSerializer(this.GetType()).Serialize(writer, this);
        }
        return doc.DocumentElement;
    }
    #endregion Methods
}

输入

XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0","utf-8",null));
XmlNode rootnode = doc.AppendChild(doc.CreateElement("Root_Node"));
XmlNode editionsNode = rootnode.AppendChild(doc.CreateElement("Editions"));

Book b = new Book();
b.Isbn = "978-0-553-10953-5";
b.Title = "A Brief History of Time";
XmlNode edition = doc.ImportNode(b.SerializeToXmlElement(), false);
editionsNode.AppendChild(edition);
edition.AppendChild(doc.CreateElement("Impressions"));

输出

<Root_Node>
    <Editions>
        <Edition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <Impressions />
        </Edition>
    </Editions>
</Root_Node>

可以告诉我如何从XML输出中的版本节点中删除xmlns:xsixmlns:xsd属性的人的奖励积分。

1 个答案:

答案 0 :(得分:1)

您需要将true的第二个参数传递给XmlDocument.ImportNode(XmlNode, Boolean)

  

  
类型:System.Boolean   
true 执行深度克隆;否则, false

这表示也应该复制传入节点的子节点。因此,您的代码应如下所示:

XmlNode edition = doc.ImportNode(b.SerializeToXmlElement(), true);

可以告诉我如何从XML输出中的版本节点中删除xmlns:xsixmlns:xsd属性的人的加分点。

正如this answer Omitting all xsi and xsd namespaces when serializing an object in .NET? 所解释的Thomas Levesque,您需要将XmlSerializerNamespaces空名称/命名空间对传递给{{} 3}}:

public XmlElement SerializeToXmlElement()
{
    XmlDocument doc = new XmlDocument();
    using (XmlWriter writer = doc.CreateNavigator().AppendChild())
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
        new XmlSerializer(this.GetType()).Serialize(writer, this, ns);
    }
    return doc.DocumentElement;
}

工作Serialize()