簡體   English   中英

如何將CDATA與從xsd.exe生成的C#類一起使用?

[英]How can I use CDATA with generated C# classes from xsd.exe?

問題

我正在嘗試填寫一個映射到xs:string並將其寫入XML。

我將這個值的生成代碼放在這篇文章的底部,因為它有點長。

以前我只是給它分配了字符串值。

rawdata.data = generatedString;

但是當我嘗試這個。

rawdata.data = "<![CDATA[" + generatedString + "]]>";

最終輸出仍然會格式化CDATA部分。

&lt;![CDATA[

有什么辦法可以避免這種情況的發生,以使CDATA像預期的那樣出現?

額外的信息

為該字段生成的代碼。

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class DataFilesRawdata
{

    private string idField;

    private string dataField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string ID
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string data
    {
        get
        {
            return this.dataField;
        }
        set
        {
            this.dataField = value;
        }
    }
}

根據微軟如何構建XML序列化程序,@ SeM的答案是我認為是最正確的解決方案,但是由於我需要相對頻繁地從XSD重新生成類,因此我決定最好尋找另一個解決方案,而不是手動編輯該解決方案。每次構建后都會生成類。

本着這種精神,我發現不必修改生成的類,而可以覆蓋XmlSerializer,這樣,如果它遇到CDATA內容,便可以處理它。

當然,這僅在CDATA位於元素的開頭和結尾時才有效。 在這方面,它適合我的用例,但不能普遍實現所有用例。

using (var fileStream = new System.IO.FileStream(tempFilePath,FileMode.Create))
{                
    var xmlwriter = new CustomXmlTextWriter(fileStream);
    xmls.Serialize(xmlwriter, contents, ns);
}

和風俗作家。

public class CustomXmlTextWriter : XmlTextWriter
{

    //... constructor if you need it

    public override void WriteString(string text)
    {
        if (text.StartsWith("<![CDATA[") && text.EndsWith("]]>"))
        {
            base.WriteRaw(text);
            return;
        }
        base.WriteString(text);
    }

}

看起來這是Microsoft采取的方針。

https://referencesource.microsoft.com/#SMDiagnostics/System/ServiceModel/Diagnostics/PlainXmlWriter.cs,137

為此 ,請使用XmlCDataSection

[XmlElement("data")]
public System.Xml.XmlCDataSection Data { get; set; }

如果序列化對象,它將在xml中自動創建CData節。

分配它:

rawdata.data = System.Xml.XmlDocument().CreateCDataSection(generatedString);

暫無
暫無

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

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