コード例 #1
0
        /// <summary>
        /// Добавляет определение в XML.
        /// </summary>
        /// <param name="definition"></param>
        public void Add(ItemDefinition definition)
        {
            if (definition == null)
            {
                throw new ArgumentNullException(nameof(definition));
            }

            string typesXmlPath = this.TypesXmlItem.GetFullPath();

            //грузим существующий XML
            XmlDocument xdoc = new XmlDocument();

            xdoc.PreserveWhitespace = false;
            xdoc.LoadXml(File.ReadAllText(typesXmlPath));

            XmlNode typeDefinitionsNode = xdoc.SelectSingleNode("TypeDefinitions");

            if (typeDefinitionsNode == null)
            {
                throw new Exception("Узел <TypeDefinitions> не найден");
            }

            //находим соответствующую секцию для типа
            XmlNode section = typeDefinitionsNode.SelectSingleNode(definition.SectionName);

            if (section == null)
            {
                //создаём секцию
                section = xdoc.CreateElement(definition.SectionName);
                typeDefinitionsNode.AppendChild(section);
            }
            else
            {
                //ищем дубликаты в секции
                XmlNode duplicateNode = section.SelectSingleNode(definition.UniqueNodeXPath);
                if (duplicateNode != null)
                {
                    if (WSSDeveloperPackage.ShowUserConfirmOkCancel($"В файле Types.xml уже есть определение по xpath: {definition.UniqueNodeXPath}.\n\nЗаменить?", "Дублирование"))
                    {
                        XmlNode parentNode;
                        if ((parentNode = duplicateNode.ParentNode) == null)
                        {
                            throw new NotificationException("Некорректный формат Types.xml");
                        }

                        section.RemoveChild(parentNode);
                    }
                    else
                    {
                        return;
                    }
                }
            }

            //вставляем XML-определение типа
            XmlDocument temp = new XmlDocument();

            temp.LoadXml(definition.CreateXml());
            section.AppendChild(xdoc.ImportNode(temp.FirstChild, true));

            //делаем чекаут Types.xml
            this.Cmd.DTE.CheckOutItem(this.TypesXmlItem);

            //сохраняем XML
            xdoc.Save(typesXmlPath);

            //открываем
            Window win = this.Cmd.DTE.ItemOperations.OpenFile(typesXmlPath, EnvDTE.Constants.vsViewKindTextView);
        }