Class 个属性被 XmlSerializer 忽略

Class properties ignored by XmlSerializer

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

图书class

[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 属性,则加分。

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

deep
 Type: System.Boolean
true to perform a deep clone; otherwise, false.

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

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

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

this answer to Omitting all xsi and xsd namespaces when serializing an object in .NET? by Thomas Levesque you need to pass an XmlSerializerNamespaces with an empty name/namespace pair into Serialize() 中所述:

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;
}

工作.Net fiddle