gpt4 book ai didi

c# - XML-(反)序列化整数的列表属性作为简单的分隔符分隔序列

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:15 28 4
gpt4 key购买 nike

我正在对一个(外部给定的)XML 文件进行操作,该文件具有以下形式的元素

<SomeElement SomeAttribute1 = "10" SomeAttribute2 = "Bla">
10 20 30 40
50 60 70 80
</SomeElement>

我知道如何将属性作为属性处理(通过使用 [XmlAttribute] ),但我不知道如何轻松地将内容主体中的空格分隔值放入 List<int> 中.

当然,我可以将内容视为字符串属性并为自己进行解析(通过创建一个单独的 [XmlIgnore] 类型为 List<int> 的属性)。

但如果有一个 C# 属性指示(反)序列化器自动执行此操作,比如(伪代码),那就更好了

public class
{
[XmlAttribute]
public int SomeAttribute1 {get; set;}

[XmlAttribute]
public int SomeAttribute2 {get; set;}

[XmlParseListAsDelimitedSequence(" ")]
public List<int> Values {get; set;}
}

有没有?

最佳答案

可能最简单的选择是序列化为文本并稍后手动解析值。你可以这样做:

[Serializable, XmlRoot("SomeElement")]
public class Foo
{
[XmlAttribute]
public int SomeAttribute1 { get; set; }

[XmlAttribute]
public int SomeAttribute2 { get; set; }

[XmlText]
public string Raw { get; set; }

[XmlIgnore]
public List<int> Values => Raw
.Split(new [] {" ", "\n"}, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
}

关于c# - XML-(反)序列化整数的列表属性作为简单的分隔符分隔序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831228/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com