Deserialize an XML file with XmlSerializer but an attribute contains a colon in its name

时间:2017-12-18 08:25:16

标签: c# .net xml xml-serialization

I have this xml file that follows this dtd: http://www.edrdg.org/jmdict/jmdict_dtd_h.html

You can notice that 2 elements contains attributes with a colon (System.getProperty("java.class.path"); ) in their name:

lsource and gloss can contain an attribute named :, as seen in this example (for the lsource element):

xml:lang

I am not how sure to define my class representing the <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> element, here it is for now, but it is missing this attribute:

lsource

How should I name the property for the XmlSerializer to properly recognize and parse the attribute? I tried adding a property [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; } } } or public string xml_lang { get; set; } but both failed to parse the attribute from the xml file when XmlSerializer.Deserialize is called

1 个答案:

答案 0 :(得分:1)

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

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

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