Browse Source

Able to save as XML, Name needs to be writable after all

Piotr Czajkowski 3 years ago
parent
commit
da04f17699
3 changed files with 30 additions and 9 deletions
  1. 11 1
      PSDText/PSDText.cs
  2. 6 8
      PSDText/TextData.cs
  3. 13 0
      PSDTextTests/PSDTextTests.cs

+ 11 - 1
PSDText/PSDText.cs

@@ -3,6 +3,7 @@ using System.Collections.Generic;
 using System.IO;
 using System.Text;
 using System.Xml;
+using System.Xml.Serialization;
 
 namespace PSDText
 {
@@ -71,7 +72,7 @@ namespace PSDText
                 var name = textNode.SelectSingleNode("./photoshop:LayerName", _ns)?.InnerText;
                 var text = textNode.SelectSingleNode("./photoshop:LayerText", _ns)?.InnerText;
 
-                data.Add(new TextData(name, text));
+                data.Add(new TextData{Name = name, Text = text});
             }
 
             return data;
@@ -86,5 +87,14 @@ namespace PSDText
             AddXMLNamespaces();
             TextData = GetTextData();
         }
+
+        public void SaveAsXML(string path)
+        {
+            var serializer = new XmlSerializer(typeof(List<TextData>));
+            using (var sr = new StreamWriter(path))
+            {
+                serializer.Serialize(sr, TextData);
+            }
+        }
     }
 }

+ 6 - 8
PSDText/TextData.cs

@@ -1,14 +1,12 @@
-namespace PSDText
+using System.Xml.Serialization;
+
+namespace PSDText
 {
     public class TextData
     {
-        public readonly string Name;
-        public string Text;
+        [XmlAttribute]
+        public string Name;
 
-        public TextData(string name, string text)
-        {
-            Name = name;
-            Text = text;
-        }
+        public string Text;
     }
 }

+ 13 - 0
PSDTextTests/PSDTextTests.cs

@@ -1,3 +1,4 @@
+using System.IO;
 using Xunit;
 
 namespace PSDTextTests
@@ -12,5 +13,17 @@ namespace PSDTextTests
             var test = new PSDText.PSDText(TestFile);
             Assert.NotEmpty(test.TextData);
         }
+
+        [Fact]
+        public void SaveAsXML()
+        {
+            var test = new PSDText.PSDText(TestFile);
+            Assert.NotEmpty(test.TextData);
+
+            var destination = "./test.xml";
+            test.SaveAsXML(destination);
+            Assert.True(File.Exists(destination));
+            File.Delete(destination);
+        }
     }
 }