【问题标题】:Serialization of PointCollection using XAML syntax使用 XAML 语法对 PointCollection 进行序列化
【发布时间】:2017-10-26 12:15:47
【问题描述】:

是否可以使用更简洁的 XAML 样式语法通过 XML 序列化读取 C# PointCollection

<Points>1,2 3,4</Points>

而不是

<Points>
    <Point>
        <X>1</X>
        <Y>2</Y>
    </Point>
    <Point>
        <X>3</X>
        <Y>4</Y>
    </Point>
</Points>

虽然我使用下面的代码可以正常工作,但如果可能的话,我更喜欢使用前者。

    [XmlElement("Points")]
    public PointCollection Points { get; set; }

【问题讨论】:

  • 一般我使用Select(x,index) => 然后使用索引值来解析数据。
  • 指定你的类的确切类型!

标签: c# xml xml-parsing


【解决方案1】:

您可以使用System.Xml.Serialization.XmlSerializer

[XmlIgnore]
public PointCollection Points { get; set; }

[XmlElement("Points")]
public string FakePoints
{
    get { return string.Join(" ", Points.Select(p => p.X + "," + p.Y)); }
    set
    {
        var collection = new PointCollection();
        foreach (var s in value.Split())
        {
            var p = s.Split(',');
            collection.Add(new Point { X = int.Parse(p[0]), Y = int.Parse(p[1]) });
        }
        Points = collection;
    }
}

我不知道您的 PointCollectionPoint 类的确切类型。或许代码可以稍微简化一下。


如果您使用System.Windows.Media.PointCollectionSystem.Windows.Point,那么您可以使用System.Xaml.XamlServices 类获得所需的结果。

using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Xaml;


public class Foo
{
    public PointCollection Points { get; set; }
}


var foo = new Foo
{
    Points = new PointCollection()
    {
        new Point { X = 1, Y = 2 },
        new Point { X = 3, Y = 4 }
    }
};

using (var fs = new FileStream("test.xml", FileMode.Create))
    XamlServices.Save(fs, foo);

using (var fs = new FileStream("test.xml", FileMode.Open))
    foo = (Foo)XamlServices.Load(fs);

结果:

<Foo Points="1,2 3,4" xmlns="clr-namespace:;assembly=ConApp" />

【讨论】:

  • 这是我的后备方法。我只是希望有一种无需编写代码的本地方法。 XAML 将紧凑格式读取到相同的结构中,因此似乎必须有办法做到这一点。
猜你喜欢
  • 2012-07-21
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 2016-03-27
相关资源
最近更新 更多