[英]How to change xml attribute while deserialization with xmlserializer c#?
Is there any way of modifying attribute value when deserializing xml using XmlSerializer?使用 XmlSerializer 反序列化 xml 时有什么方法可以修改属性值?
For instance, I have such xml:例如,我有这样的 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?我想将
chunk
元素反序列化为Chunk
class 并将属性id="ch1"
设置为Id
属性 - 有没有办法修剪这个ch
substring 并将数字1
分配给 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.我已经阅读了一些MSDN文档,但没有找到任何解决方案。
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.
我知道实现所需结果的唯一方法是使用 [XmlIgnore] 并专门为字符串化的 xml ID 创建第二个属性,并为您的内部 integer 值创建一个本地化的转换器属性。 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].序列化程序将照常对 [XmlAttribute] 进行操作,但会通过 [XmlIgnore]。 Your c# code could use either.
您的 c# 代码可以使用其中任何一个。 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.
不幸的是,XmlSerializer 需要公共属性,因此您无法从代码中隐藏_id_xml属性,但您可以使用 [Obsolete] 在编译器中发出警告信号。
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.您可以使用 _id_xml getter & setter 与 int 进行转换,但在序列化期间管理错误时这样做可能会出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.