簡體   English   中英

.NET XML序列化程序和對象屬性中的XHTML字符串

[英].NET XML serializer and XHTML string in object property

我有一堂課

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.7.3081.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://test/v1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://test/v1", IsNullable=false)]
public partial class Data
{
    ...
    public object Comment { get; set; }
    ...
}

Comment屬性屬於object類型,因為在xml模式中將其聲明為any類型。 聲明為any允許文本和xhtml數據。 我無法更改架構-它與國際標准有關。

單行內容(字符串):

<Comment>This is a single line text</Comment>

多行內容(xhtml):

<Comment>
   <div xmlns="http://www.w3.org/1999/xhtml">This is text<br />with line breaks<br />multiple times<div>
</Comment>

XmlSerializer不允許我將XmlElement插入自動生成的Data類的object Comment屬性中。 我還嘗試過為XHtml創建自定義IXmlSerializer實現,但是隨后需要將XSD生成的Comment屬性聲明為該確切類型(而不是對象)。

我要在Comment屬性上設置的自定義XHtml類型如下所示;

[XmlRoot]
public class XHtmlText : IXmlSerializable
{
    [XmlIgnore]
    public string Content { get; set; }

    public XmlSchema GetSchema() => null;

    public void ReadXml(XmlReader reader) { } // Only used for serializing to XML

    public void WriteXml(XmlWriter writer)
    {
        if (Content.IsEmpty()) return;

        writer.WriteStartElement("div", "http://www.w3.org/1999/xhtml");
        var lines = Content.Split('\n');
        for (var i = 0; i < lines.Length; i++)
        {
            var line = lines[i];
            writer.WriteRaw(line);
            if (i < lines.Length - 1) writer.WriteRaw("<br />");
        }
        writer.WriteFullEndElement();
    }
}

XmlSerializer的異常:

InvalidOperationException:在這種情況下可能不會使用Lib.Xml.XHtmlText類型。 要將Lib.Xml.XHtmlText用作參數,返回類型或類或結構的成員,必須將參數,返回類型或成員聲明為Lib.Xml.XHtmlText類型(不能為對象)。 Lib.Xml.XHtmlText類型的對象不能在未類型化的集合中使用,例如ArrayLists

序列化代碼:

    var data = new Lib.Xml.Data { Content = "test\ntest\ntest\n" };

    var settings = new XmlWriterSettings()
    {
        NamespaceHandling = NamespaceHandling.OmitDuplicates,
        Indent = false,
        OmitXmlDeclaration = omitDeclaration,
    };

    using (var stream = new MemoryStream())
    using (var xmlWriter = XmlWriter.Create(stream, settings))
    {
        var serializer = new XmlSerializer(data.GetType(), new[] { typeof(Lib.Xml.XHtmlText) });
        serializer.Serialize(xmlWriter, data);
        return stream.ToArray();
    }

看來我已經找到了解決方案。

我無法將注釋設置為XmlElement的實例

data.Comment = commentAsXhtmlXmlElement;

但是我可以(以某種方式)分配一個XmlNode數組

data.Comment = new XmlNode[] { commentAsXhtmlXmlElement };

當我反序列化數據POCO的入站xml實例時發現。

奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM