LabelAssociation.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.IO;
  2. using System.Text;
  3. using System.Xml;
  4. namespace AIPractice.Shared.Labels
  5. {
  6. public class LabelAssociation
  7. {
  8. /// <summary>
  9. /// Gets the left label.
  10. /// </summary>
  11. public ImageLabel Left { get; }
  12. /// <summary>
  13. /// Gets the right label.
  14. /// </summary>
  15. public ImageLabel Right { get; }
  16. public LabelAssociation(ImageLabel left, ImageLabel right)
  17. {
  18. Left = left;
  19. Right = right;
  20. }
  21. public static LabelAssociation FromXml(string xmlContent)
  22. {
  23. ImageLabel left = null;
  24. ImageLabel right = null;
  25. using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(xmlContent)))
  26. {
  27. using (XmlReader r = XmlReader.Create(ms))
  28. {
  29. r.Read();
  30. while (r.NodeType == XmlNodeType.Element &&
  31. (r.Name == nameof(DescriptionLabel) ||
  32. r.Name == nameof(ConclusionLabel)) || r.Read())
  33. {
  34. if (r.NodeType == XmlNodeType.EndElement && r.Name == nameof(LabelAssociation))
  35. {
  36. break;
  37. }
  38. if (r.Name == nameof(DescriptionLabel) && left == null)
  39. {
  40. left = DescriptionLabel.FromXml(r.ReadOuterXml());
  41. }
  42. if (r.Name == nameof(DescriptionLabel) && left != null && right == null)
  43. {
  44. right = DescriptionLabel.FromXml(r.ReadOuterXml());
  45. }
  46. if (r.Name == nameof(ConclusionLabel) && left == null)
  47. {
  48. left = ConclusionLabel.FromXml(r.ReadOuterXml());
  49. }
  50. if (r.Name == nameof(ConclusionLabel) && left != null && right == null)
  51. {
  52. right = ConclusionLabel.FromXml(r.ReadOuterXml());
  53. }
  54. }
  55. return new LabelAssociation(left, right);
  56. }
  57. }
  58. }
  59. public string ToXml()
  60. {
  61. var sb = new StringBuilder();
  62. sb.Append($"<{nameof(LabelAssociation)}>");
  63. sb.Append(Left.ToXml());
  64. sb.Append(Right.ToXml());
  65. sb.Append($"</{nameof(LabelAssociation)}>");
  66. return sb.ToString();
  67. }
  68. }
  69. }