简体   繁体   中英

How to change xml attribute while deserialization with xmlserializer c#?

Is there any way of modifying attribute value when deserializing xml using XmlSerializer?

For instance, I have such xml:

<chunkList>
   <chunk id="ch1" type="p">
      <sentence id="s1">
         <tok>
            <orth>XXX</orth>
            <lex disamb="1">
               <base>XXX</base>
               <ctag>subst:sg:nom:f</ctag>
            </lex>
         </tok>
      </sentence>
   </chunk>
</chunkList>

I want to deserialize chunk element into Chunk class and set attribute id="ch1" to Id property - is there any way of trimming this ch substring and asigning number 1 to property of type int?

[XmlAttribute("id")] //maybe there is some attribute to achive this?
public int Id { get; set; }

I have read some of MSDN documentation but didn't found any solution.

There is no elegant way to achieve this using a single attribute. The only way I know to achieve the desired result is to make use of [XmlIgnore] and to create a second property specifically for the stringified xml ID, and a localized converter property for your internal integer value. Some along the lines of:

[XmlAttribute("id")] 
public string _id_xml {get; set;}

 [XmlIgnore]
 public int Id {
        // convert local copy of xml attribute value to/from int.
        get => int.Parse(_id_xml.Replace("ch",""));
        set => _id_xml = $"ch{value}";
   }

My converter here is very basic and clearly you will need to improve it and consider error handling.

The serializer will operate against the [XmlAttribute] as normal, but pass over the [XmlIgnore]. Your c# code could use either. Unfortunately, the XmlSerializer requires public properties, so you can not hide the _id_xml property from your code, but you could use [Obsolete] to signal a warning in the compiler.

You could do the conversion to/from int with the _id_xml getter & setter, but doing this could be problematic when managing errors during serialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM