使用XmlSerializer反序列化XML文件,但属性的名称中包含冒号

问题描述 投票:0回答:1

我有这个跟随这个dtd的xml文件:http://www.edrdg.org/jmdict/jmdict_dtd_h.html

您可以注意到2个元素包含名称中带冒号(:)的属性:

lsource和gloss可以包含一个名为xml:lang的属性,如本例所示(对于lsource元素):

<entry>
    <ent_seq>1002480</ent_seq>
    <k_ele>
        <keb>お転婆</keb>
    </k_ele>
    <k_ele>
        <keb>御転婆</keb>
    </k_ele>
    <r_ele>
        <reb>おてんば</reb>
    </r_ele>
    <sense>
        <pos>&adj-na;</pos>
        <pos>&n;</pos>
        <misc>&uk;</misc>
        <lsource xml:lang="dut">ontembaar</lsource>
        <gloss>tomboy</gloss>
    </sense>
</entry>

我不确定如何定义代表lsource元素的类,这里现在是这样,但它缺少这个属性:

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.7.2046.0")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "JMdict_e.dtd")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "JMdict_e.dtd", IsNullable = false)]
    public partial class lsource
    {
        private string ls_typeField;

        private string ls_waseiField;

        private string valueField;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string ls_type
        {
            get
            {
                return this.ls_typeField;
            }
            set
            {
                this.ls_typeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string ls_wasei
        {
            get
            {
                return this.ls_waseiField;
            }
            set
            {
                this.ls_waseiField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        public string Value
        {
            get
            {
                return this.valueField;
            }
            set
            {
                this.valueField = value;
            }
        }
    }

我应该如何为XmlSerializer命名属性以正确识别和解析属性?我尝试添加属性public string xml_lang { get; set; }public string lang { get; set; }但是当调用XmlSerializer.Deserialize时,两者都无法解析xml文件中的属性

c# .net xml xml-serialization
1个回答
1
投票

该属性位于未生成的名称空间中,因此很容易忽略元素/属性。使用它所在的命名空间来装饰lang属性将起作用:

[System.Xml.Serialization.XmlAttributeAttribute(Namespace = "http://www.w3.org/XML/1998/namespace")]
public string lang {
    get;set;
}

xml命名空间是W3C定义的标准命名空间。它的价值可以找到here

© www.soinside.com 2019 - 2024. All rights reserved.