XGML_Reader.cs

90 lines | 2.582 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Xml.Linq;
using System.Xml;

using yEd.XGML.IO.Read;
using yEd.XGML.DocumentEntities;

namespace yEd.XGML.IO
{
    /// <summary>
    /// Класс для считывагия yed XGML файла в модель Document
    /// </summary>
    public class XGML_Reader : BaseIO
    {
        public Document Read(XDocument xdoc)
        {
            Document res = new Document();
            base.SetCulture_en_US();


            XElement root = xdoc.Element("section");


            res.Creator = root.GetChild_Attribute("Creator").Value;
            res.Version = root.GetChild_Attribute("Version").Value;


            var SectionGraph = root.GetChild_Section("graph");

            var GraphElements = SectionGraph.Elements()
                .Where(e => e.Name == "section");

            NodeGroupReader nodeGroupReader = new NodeGroupReader();
            NodeReader nodeReader = new NodeReader();
            EdgeReader edgeReader = new EdgeReader();

            foreach (XElement elem in GraphElements)
            {
                if (elem.Attribute("name").Value == "node")
                {                   
                    if (elem.GetChild_Attribute("isGroup") != null)
                    {
                        var group = nodeGroupReader.Read(elem);
                        res.Elements.Add(group.id, group);
                    }
                    else
                    {
                        var node = nodeReader.Read(elem);
                        res.Elements.Add(node.id, node);
                    }
                }
                else if (elem.Attribute("name").Value == "edge")
                {
                    res.Edges.Add(edgeReader.Read(elem));
                }
            }

            base.RestoreCulture();
            return res;
        }

        public Document Read(string file) =>        
            Read(XDocument.Load(file));        
        
        public Document Read(Stream stream) =>
            Read(XDocument.Load(stream));



        /// <summary>
        /// Костыль из за того, что yEd ставит в аттрибуте кривую(для  c# xml) кодировку
        /// </summary>
        /// <param name="FileName"></param>
        public static void DropEncodingAttribute(string FileName)
        {
            var xml_doc = File.ReadAllLines(FileName);
            xml_doc[0] = "<?xml version=\"1.0\"?>";
            File.WriteAllLines(FileName, xml_doc);
        }

    }

}