C# (CSharp) System.Xml.Linq. XElement Code Examples

C# (CSharp) System.Xml.Linq.XElement - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для System.Xml.Linq.XElement, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
        public System.Xml.Linq.XElement ToPhysical(System.Xml.Linq.XElement udsService)
        {
            string name = udsService.Attribute("Name").Value;
            XElement x = new XElement("Service", new XAttribute("Name", name));
            XElement prop = new XElement("Property", new XAttribute("Name", "Definition"));
            x.Add(prop);

            XElement serv = new XElement("Service");
            prop.Add(serv);

            XElement sd = new XElement("ServiceDescription");
            serv.Add(sd);

            XElement handler = new XElement("Handler", new XAttribute("ExecType", "RemoteComponent"));
            sd.Add(handler);
            
            XElement udsDefinition = udsService.Element("Definition");
            foreach (XElement e in udsDefinition.Elements())
                sd.Add(e);

            XElement usage = new XElement("Usage");
            sd.Add(usage);

            XElement sh = new XElement("ServiceHelp");
            sh.Add(new XElement("Description"));
            sh.Add(new XElement("RequestSDDL"));
            sh.Add(new XElement("ResponseSDDL"));
            sh.Add(new XElement("Errors"));
            sh.Add(new XElement("RelatedDocumentServices"));
            sh.Add(new XElement("Samples"));
            serv.Add(sh);
            return x;
        }
Пример #2
0
        public static TableCellStyle CreateFromXElement(XElement element)
        {
            TableCellStyle cellStyle = new TableCellStyle();
            cellStyle.PopulateFromXElement(element);

            return cellStyle;
        }
 public override XElement Serialize()
 {
     XElement thisElement = new XElement(GetType().Name);
     thisElement.Add(insideEquation.Serialize());
     thisElement.Add(outerEquation.Serialize());
     return thisElement;
 }
Пример #4
0
        public void AddNextObxElement(string value, XElement document, string observationResultStatus)
        {
            XElement obxElement = new XElement("OBX");
            XElement obx01Element = new XElement("OBX.1");
            XElement obx0101Element = new XElement("OBX.1.1", this.m_ObxCount.ToString());
            obx01Element.Add(obx0101Element);
            obxElement.Add(obx01Element);

            XElement obx02Element = new XElement("OBX.2");
            XElement obx0201Element = new XElement("OBX.2.1", "TX");
            obx02Element.Add(obx0201Element);
            obxElement.Add(obx02Element);

            XElement obx03Element = new XElement("OBX.3");
            XElement obx0301Element = new XElement("OBX.3.1", "&GDT");
            obx03Element.Add(obx0301Element);
            obxElement.Add(obx03Element);

            XElement obx05Element = new XElement("OBX.5");
            XElement obx0501Element = new XElement("OBX.5.1", value);
            obx05Element.Add(obx0501Element);
            obxElement.Add(obx05Element);

            XElement obx11Element = new XElement("OBX.11");
            XElement obx1101Element = new XElement("OBX.11.1", observationResultStatus);
            obx11Element.Add(obx1101Element);
            obxElement.Add(obx11Element);

            this.m_ObxCount++;
            document.Add(obxElement);
        }
Пример #5
0
        public static XElement ToXml(ConvolutionFilter filter)
        {
            var res = new XElement(TAG_NAME,
                new XAttribute("divisor", CommonFormatter.Format(filter.Divisor)),
                new XAttribute("bias", CommonFormatter.Format(filter.Bias))
            );

            var xMatrix = new XElement("matrix");
            for (var y = 0; y < filter.MatrixY; y++) {
                var xRow = new XElement("r");
                for (var x = 0; x < filter.MatrixX; x++) {
                    var xCol = new XElement("c") { Value = CommonFormatter.Format(filter.Matrix[y, x]) };
                    xRow.Add(xCol);
                }
                xMatrix.Add(xRow);
            }
            res.Add(xMatrix);

            res.Add(new XElement("color", XColorRGBA.ToXml(filter.DefaultColor)));
            if (filter.Reserved != 0) {
                res.Add(new XAttribute("reserved", filter.Reserved));
            }
            res.Add(new XAttribute("clamp", CommonFormatter.Format(filter.Clamp)));
            res.Add(new XAttribute("preserveAlpha", CommonFormatter.Format(filter.PreserveAlpha)));
            return res;
        }
        protected override object GetValueFromXml(XElement root, XName name, PropertyInfo prop)
        {
            var isAttribute = false;

            // Check for the DeserializeAs attribute on the property
            var options = prop.GetAttribute<DeserializeAsAttribute>();

            if (options != null)
            {
                name = options.Name ?? name;
                isAttribute = options.Attribute;
            }

            if (isAttribute)
            {
                var attributeVal = GetAttributeByName(root, name);

                if (attributeVal != null)
                {
                    return attributeVal.Value;
                }
            }

            return base.GetValueFromXml(root, name, prop);
        }
Пример #7
0
        public void RunFromInput(string inputDir, string outputFile, string name)
        {
            // setup XML file
            XNamespace ns = "http://schemas.microsoft.com/wix/2006/wi";
            XElement componentGroup = new XElement(ns + "ComponentGroup", new XAttribute("Id", "Component_" + name));
            XElement directoryRef = new XElement(ns + "DirectoryRef", new XAttribute("Id", "Dir_" + name));

            // build content
            AddDirectory(inputDir, "Component_Generated_" + name, "Dir_Generated_" + name, ns, directoryRef, componentGroup);

            // save
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", ""),
                new XElement(ns + "Wix",
                    new XAttribute("xmlns", ns.NamespaceName),
                    new XComment(String.Format(
                        "Autogenerated at {0} for directory {1}",
                        DateTime.Now.ToString("dd MMM yyy HH:mm", System.Globalization.CultureInfo.InvariantCulture),
                        inputDir
                    )),
                    new XElement(ns + "Fragment", componentGroup),
                    new XElement(ns + "Fragment", directoryRef)
                )
            );
            doc.Save(outputFile);
            OutputStream.WriteLine("Done!");
        }
Пример #8
0
        internal CharacterAttachmentBrand(CharacterAttachmentSlot slot, XElement element)
        {
            Slot = slot;

            // Set up strings
            var brandNameAttribute = element.Attribute("Name");
            if (brandNameAttribute != null)
                Name = brandNameAttribute.Value;

            var brandThumbnailAttribute = element.Attribute("Thumbnail");
            if (brandThumbnailAttribute != null)
                ThumbnailPath = brandThumbnailAttribute.Value;

            // Get attachments
            var slotAttachmentElements = element.Elements("Attachment");

            int count = slotAttachmentElements.Count();
            if (Slot.CanBeEmpty)
                count++;

            var slotAttachments = new CharacterAttachment[count];

            for (int i = 0; i < slotAttachmentElements.Count(); i++)
            {
                var slotAttachmentElement = slotAttachmentElements.ElementAt(i);

                slotAttachments[i] = new CharacterAttachment(Slot, slotAttachmentElement);
            }

            if (Slot.CanBeEmpty)
                slotAttachments[slotAttachmentElements.Count()] = new CharacterAttachment(Slot, null);

            Attachments = slotAttachments;
        }
Пример #9
0
        public XElement Format(Scenario scenario, int id)
        {
            var header = new XElement(
                this.xmlns + "div",
                new XAttribute("class", "scenario-heading"),
                new XElement(this.xmlns + "h2", scenario.Name));

            var tags = RetrieveTags(scenario);
            if (tags.Length > 0)
            {
                var paragraph = new XElement(this.xmlns + "p", CreateTagElements(tags.OrderBy(t => t).ToArray(), this.xmlns));
                paragraph.Add(new XAttribute("class", "tags"));
                header.Add(paragraph);
            }

            header.Add(this.htmlDescriptionFormatter.Format(scenario.Description));

            return new XElement(
                this.xmlns + "li",
                new XAttribute("class", "scenario"),
                this.htmlImageResultFormatter.Format(scenario),
                header,
                new XElement(
                    this.xmlns + "div",
                    new XAttribute("class", "steps"),
                    new XElement(
                        this.xmlns + "ul",
                        scenario.Steps.Select(step => this.htmlStepFormatter.Format(step)))));
        }
 private void GenerateNamespaceMapping(XElement namespaces) {
     if (namespaces == null)
         return;
     foreach(XElement ns in namespaces.Elements(XName.Get("Namespace", Constants.TypedXLinqNs))) {
         namespaceMapping.Add((string)ns.Attribute(XName.Get("Schema")), (string)ns.Attribute(XName.Get("Clr")));
     }
 }
        public IEnumerable<JObject> ReadElement(IAixmConverter converter, JObject currentObject, XElement element)
        {
            currentObject.AddToProperties("elevation", JObject.FromObject(element));

            //If not a feature return null;
            return Enumerable.Empty<JObject>();
        }
Пример #12
0
        private SoundInfo LoadSound(XElement soundNode, string basePath)
        {
            SoundInfo sound = new SoundInfo { Name = soundNode.RequireAttribute("name").Value };

            sound.Loop = soundNode.TryAttribute<bool>("loop");

            sound.Volume = soundNode.TryAttribute<float>("volume", 1);

            XAttribute pathattr = soundNode.Attribute("path");
            XAttribute trackAttr = soundNode.Attribute("track");
            if (pathattr != null)
            {
                sound.Type = AudioType.Wav;
                sound.Path = FilePath.FromRelative(pathattr.Value, basePath);
            }
            else if (trackAttr != null)
            {
                sound.Type = AudioType.NSF;

                int track;
                if (!trackAttr.Value.TryParse(out track) || track <= 0) throw new GameXmlException(trackAttr, "Sound track attribute must be an integer greater than zero.");
                sound.NsfTrack = track;

                sound.Priority = soundNode.TryAttribute<byte>("priority", 100);
            }
            else
            {
                sound.Type = AudioType.Unknown;
            }

            return sound;
        }
Пример #13
0
 public void setUpdateData(XElement updatedata)
 {
     // XElement in ein character Struct konvertieren
     e4dnd2obsidian.e4DndCharakter cnv = new e4dnd2obsidian.e4DndCharakter(updatedata);
     character chrdata = cnv.getCharakterData();
     state.SetUpdateData(this, chrdata);
 }
        public void GenerateXml_InterfaceDynamicallyImplemented()
        {
            var targetType = new InvolvedType (typeof (TargetClass3));

              var mixinConfiguration = MixinConfiguration.BuildNew ().ForClass<TargetClass3> ().AddMixin<Mixin4> ().BuildConfiguration ();
              targetType.ClassContext = new ReflectedObject (mixinConfiguration.ClassContexts.First ());
              targetType.TargetClassDefinition = new ReflectedObject (TargetClassDefinitionUtility.GetConfiguration (targetType.Type, mixinConfiguration));
              var mixinContext = targetType.ClassContext.GetProperty ("Mixins").First ();
              var mixinDefinition = targetType.TargetClassDefinition.CallMethod ("GetMixinByConfiguredType", mixinContext.GetProperty ("MixinType").To<Type> ());

              var assemblyIdentifierGenerator = new IdentifierGenerator<Assembly> ();

              var output = new TargetCallDependenciesReportGenerator (mixinDefinition, assemblyIdentifierGenerator,
                                                             _remotionReflector, _outputFormatter).GenerateXml ();

              var expectedOutput = new XElement ("TargetCallDependencies",
                                        new XElement ("Dependency",
                                                     new XAttribute ("assembly-ref", "0"),
                                                     new XAttribute ("namespace", "System"),
                                                     new XAttribute ("name", "IDisposable"),
                                                     new XAttribute ("is-interface", true),
                                                     new XAttribute ("is-implemented-by-target", false),
                                                     new XAttribute ("is-added-by-mixin", false),
                                                     new XAttribute ("is-implemented-dynamically", true)));

              XElementComparisonHelper.Compare (output, expectedOutput);
        }
Пример #15
0
        public static MusicInfo FromXml(XElement musicNode, string basePath)
        {
            MusicInfo music = new MusicInfo();

            var introNode = musicNode.Element("Intro");
            var loopNode = musicNode.Element("Loop");

            XAttribute trackAttr = musicNode.Attribute("nsftrack");

            if (introNode != null || loopNode != null)
            {
                music.Type = AudioType.Wav;
                if (introNode != null) music.IntroPath = FilePath.FromRelative(introNode.Value, basePath);
                if (loopNode != null) music.LoopPath = FilePath.FromRelative(loopNode.Value, basePath);
            }
            else if (trackAttr != null)
            {
                music.Type = AudioType.NSF;

                int track;
                if (!trackAttr.Value.TryParse(out track) || track <= 0) throw new GameXmlException(trackAttr, "Sound track attribute must be an integer greater than zero.");
                music.NsfTrack = track;
            }
            else
            {
                music.Type = AudioType.Unknown;
            }

            return music;
        }
        public static string Build()
        {
            bool value = false;
            string message = "Fail!";
            XElement result = new XElement("Result");

            try
            {
                using (PlayerBussiness db = new PlayerBussiness())
                {
                    BestEquipInfo[] infos = db.GetCelebByDayBestEquip();
                    foreach (BestEquipInfo info in infos)
                    {
                        result.Add(FlashUtils.CreateBestEquipInfo(info));
                    }

                    value = true;
                    message = "Success!";
                }
            }
            catch (Exception ex)
            {
                log.Error("Load CelebByDayBestEquip is fail!", ex);
            }

            result.Add(new XAttribute("value", value));
            result.Add(new XAttribute("message", message));

            return csFunction.CreateCompressXml(result, "CelebForBestEquip", false);
        }
Пример #17
0
        /// <summary>
        /// Injects Calibre's metadata into XHTML element (for metadata part)
        /// </summary>
        /// <param name="metadata"></param>
        public void InjectData(XElement metadata)
        {
            if (!string.IsNullOrEmpty(SeriesName))
            {
                XElement serie = new XElement(MetaName);
                serie.Add(new XAttribute("name", "calibre:series"));
                serie.Add(new XAttribute("content", SeriesName));
                metadata.Add(serie);
            }

            if (SeriesIndex != 0)
            {
                XElement serieIndex = new XElement(MetaName);
                serieIndex.Add(new XAttribute("name", "calibre:series_index"));
                serieIndex.Add(new XAttribute("content", SeriesIndex));
                metadata.Add(serieIndex);
            }

            if (!string.IsNullOrEmpty(TitleForSort))
            {
                XElement title4Sort = new XElement(MetaName);
                title4Sort.Add(new XAttribute("name", "calibre:title_sort"));
                title4Sort.Add(new XAttribute("content", TitleForSort));
                metadata.Add(title4Sort);
            }

            XElement date = new XElement(MetaName);
            date.Add(new XAttribute("name", "calibre:timestamp"));
            date.Add(new XAttribute("content", DateTime.UtcNow.ToString("O")));
            metadata.Add(date);
        }
    public static GameObject buildObjectFromXML(XElement xmlObject)
    {
        string objectName = (xmlObject.Attribute("name") != null) ? ((string)xmlObject.Attribute("name")) : ("Unit Map Object");
        string sprite = "testTile_White_Black";

        return generateObject(objectName, sprite);
    }
        protected override XElement Validate(XElement item)
        {
            // Validate with XSD
            XElement xsdErrors = this.ValidateXSD(item, HttpContext.Current.Server.MapPath(@"~\Xslt\Senior\Senior.xsd"));
            if (xsdErrors != null && xsdErrors.Elements("Error").Count() > 0)
            {
                return xsdErrors;
            }

            // Validate with Stored Proc
            string result = string.Empty;
            using (Persistence oDB = new Persistence())
            {
                Persistence.ParameterCollection parameters = new Persistence.ParameterCollection();
                parameters.Add("InputXml");
                parameters[0].Value = item.ToString();
                oDB.Execute("Masters_ConnectionString", "ValidateSeniorData", parameters, out result);
            }

            if (!string.IsNullOrEmpty(result))
            {
                XElement spErrors = XElement.Parse(result);
                spErrors.Elements("Error").Where(e => string.IsNullOrEmpty(e.Value)).Remove();

                if (spErrors.Elements("Error").Count() > 0)
                {
                    return spErrors;
                }
            }

            // SUCCESS!
            return null;

        }
        public void Execute(ClientContext ctx, string listTitle, XElement schema, Action<Field> setAdditionalProperties = null)
        {
            var displayName = schema.Attribute("DisplayName").Value;
            Logger.Verbose($"Started executing {nameof(CreateColumnOnList)} for column '{displayName}' on list '{listTitle}'");

            var list = ctx.Web.Lists.GetByTitle(listTitle);
            var fields = list.Fields;
            ctx.Load(fields);
            ctx.ExecuteQuery();

            // if using internal names in code, remember to encode those before querying, e.g., 
            // space character becomes "_x0020_" as described here:
            // http://www.n8d.at/blog/encode-and-decode-field-names-from-display-name-to-internal-name/
            // We don't use the internal name here because it's limited to 32 chacters. This means
            // "Secondary site abcde" is the longest possible internal name when taken into account
            // the "_x0020_" character. Using a longer name will truncate the internal name to 32
            // characters. Thus querying on the complete, not truncated name, will always return no
            // results which causes the field get created repetedly.
            var field = fields.SingleOrDefault(f => f.Title == displayName);
            if (field != null)
            {
                Logger.Warning($"Column '{displayName}' already on list {listTitle}");
                return;
            }

            var newField = list.Fields.AddFieldAsXml(schema.ToString(), true, AddFieldOptions.DefaultValue);
            ctx.Load(newField);
            ctx.ExecuteQuery();

            if (setAdditionalProperties != null)
            {
                setAdditionalProperties(newField);
                newField.Update();
            }
        }
        private static RegionDayOfWeek[] GetRegionDayOfWeeks(XElement weekDataElement, string elementName)
        {
            List<XElement> firstDaysCountElements = weekDataElement.Elements(elementName).ToList();
            if (firstDaysCountElements.Count > 0)
            {
                List<RegionDayOfWeek> firstDaysCounts = new List<RegionDayOfWeek>();
                foreach (XElement firstDaysCountElement in firstDaysCountElements)
                {
                    RegionDayOfWeek regionDayOfWeek = new RegionDayOfWeek();
                    regionDayOfWeek.DayOfWeek = GetDayOfWeek(firstDaysCountElement.Attribute("day").Value.ToString());
                    regionDayOfWeek.RegionIds = firstDaysCountElement.Attribute("territories").Value.ToString().Split(' ');

                    if (firstDaysCountElement.Attribute("alt") != null)
                    {
                        regionDayOfWeek.Alt = firstDaysCountElement.Attribute("alt").Value.ToString();
                    }

                    if (firstDaysCountElement.Attribute("references") != null)
                    {
                        regionDayOfWeek.References = firstDaysCountElement.Attribute("references").Value.ToString();
                    }

                    firstDaysCounts.Add(regionDayOfWeek);
                }

                return firstDaysCounts.ToArray();
            }

            return null;
        }
Пример #22
0
        /// <summary>
        /// Get the entity GUID for a document element of the XML file (maybe the last GUID or the next 
        /// one... depends on some rules).
        /// </summary>
        public Guid GetGuid(XElement element, string languageFallback)
        {
            Guid entityGuid;

            var elementGuid = element.GetChildElementValue(DocumentNodeNames.EntityGuid);
            if (string.IsNullOrEmpty(elementGuid))
            {
                var elementLanguage = element.GetChildElementValue(DocumentNodeNames.EntityLanguage);
                if (elementLanguage == languageFallback || string.IsNullOrEmpty(elementLanguage))
                {   // If the element does not have a GUID and the element has data for the default
                    // language, create a new GUID
                    entityGuid = Guid.NewGuid();
                }
                else
                {
                    entityGuid = entityGuidLast;
                }
            }
            else
            {
                entityGuid = Guid.Parse(elementGuid);
            }

            entityGuidLast = entityGuid;
            return entityGuid;
        }
Пример #23
0
        public static ConvolutionFilter FromXml(XElement xFilter)
        {
            var xMatrix = xFilter.RequiredElement("matrix");
            var xReserved = xFilter.Attribute("reserved");

            var filter = new ConvolutionFilter {
                Divisor = xFilter.RequiredDoubleAttribute("divisor"),
                Bias = xFilter.RequiredDoubleAttribute("bias")
            };

            var xRows = xMatrix.Elements().ToList();
            var height = xRows.Count;
            var width = xMatrix.Elements().First().Elements().Count();

            filter.Matrix = new double[height, width];
            for (var y = 0; y < filter.MatrixY; y++) {
                var xRow = xRows[y];
                var xCols = xRow.Elements().ToList();
                for (var x = 0; x < filter.MatrixX; x++) {
                    var xCol = xCols[x];
                    filter.Matrix[y, x] = CommonFormatter.ParseDouble(xCol.Value);
                }
            }

            filter.DefaultColor = XColorRGBA.FromXml(xFilter.RequiredElement("color").Element("Color"));
            if (xReserved != null) {
                filter.Reserved = byte.Parse(xReserved.Value);
            }
            filter.Clamp = xFilter.RequiredBoolAttribute("clamp");
            filter.PreserveAlpha = xFilter.RequiredBoolAttribute("preserveAlpha");
            return filter;
        }
Пример #24
0
        /// <summary>
        /// Initializes a new instance of the EnumDefinition class
        /// Populates this object with information extracted from the XML
        /// </summary>
        /// <param name="theNode">XML node describing the Enum object</param>
        /// <param name="manager">The data dictionary manager constructing this type.</param>
        public EnumDefinition(XElement theNode, DictionaryManager manager)
            : base(theNode, TypeId.EnumType)
        {
            // ByteSize may be set either directly as an integer or by inference from the Type field.
            // If no Type field is present then the type is assumed to be 'int'
            if (theNode.Element("ByteSize") != null)
            {
                SetByteSize(theNode.Element("ByteSize").Value);
            }
            else
            {
                string baseTypeName = theNode.Element("Type") != null ? theNode.Element("Type").Value : "int";

                BaseType = manager.GetElementType(baseTypeName);
                BaseType = DictionaryManager.DereferenceTypeDef(BaseType);

                FixedSizeBytes = BaseType.FixedSizeBytes.Value;
            }

            // Common properties are parsed by the base class.
            // Remaining properties are the Name/Value Literal elements
            List<LiteralDefinition> theLiterals = new List<LiteralDefinition>();
            foreach (var literalNode in theNode.Elements("Literal"))
            {
                theLiterals.Add(new LiteralDefinition(literalNode));
            }

            m_Literals = new ReadOnlyCollection<LiteralDefinition>(theLiterals);

            // Check the name. If it's null then make one up
            if (theNode.Element("Name") == null)
            {
                Name = String.Format("Enum_{0}", Ref);
            }
        }
        static void Main()
        {
            var context = new GeographyEntities();
            var xmlDocInput = XDocument.Load("../../rivers-query.xml");
            var queryResults = new XElement("results");
            foreach (var queryElement in xmlDocInput.XPathSelectElements("/queries/query"))
            {
                var riversQuery = BuildRiversQuery(context, queryElement);
                var riversElement = new XElement("rivers");
                riversElement.Add(new XAttribute("total-count", riversQuery.Count().ToString()));
                var maxResultsAttribute = queryElement.Attribute("max-results");
                if (maxResultsAttribute != null)
                {
                    int maxResults = int.Parse(maxResultsAttribute.Value);
                    riversQuery = riversQuery.Take(maxResults);
                }
                var riverNames = riversQuery.Select(r => r.RiverName).ToList();
                foreach (var riverName in riverNames)
                {
                    riversElement.Add(new XElement("river", riverName));
                }
                riversElement.Add(new XAttribute("listed-count", riversQuery.Count().ToString()));
                queryResults.Add(riversElement);
            }

            Console.WriteLine(queryResults);
        }
Пример #26
0
        public void CreateFolders(Project currentProject, string schedule, string projectName, string relativePath)
        {
            //Create a File under Properties Folder which will contain information about all WebJobs
            //https://github.com/ligershark/webjobsvs/issues/6

            // Check if the WebApp is C# or VB
            string dir = GetProjectDirectory(currentProject);
            var propertiesFolderName = "Properties";
            if (currentProject.CodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVB)
            {
                propertiesFolderName = "My Project";
            }

            DirectoryInfo info = new DirectoryInfo(Path.Combine(dir, propertiesFolderName));

            string readmeFile = Path.Combine(info.FullName, "WebJobs.xml");

            // Copy File if it does not exit
            if (!File.Exists(readmeFile))
                AddReadMe(readmeFile);

            //Add a WebJob info to it
            XDocument doc = XDocument.Load(readmeFile);
            XElement root = new XElement("WebJob");
            root.Add(new XAttribute("Project", projectName));
            root.Add(new XAttribute("RelativePath", relativePath));
            root.Add(new XAttribute("Schedule", schedule));
            doc.Element("WebJobs").Add(root);
            doc.Save(readmeFile);
            currentProject.ProjectItems.AddFromFile(readmeFile);
        }
 public override void DeSerialize(XElement xElement)
 {
     var elements = xElement.Elements().ToArray();
     insideEquation.DeSerialize(elements[0]);
     outerEquation.DeSerialize(elements[1]);
     CalculateSize();
 }
        public static void Main()
        {
            var context = new GeographyEntities();
            var countries = context.Countries;

            var countriesQuery = countries
                .Where(c => c.Monasteries.Any())
                .OrderBy(c => c.CountryName)
                .Select(c => new
                {
                    c.CountryName,
                    Monasteries = c.Monasteries
                        .OrderBy(m => m.Name)
                        .Select(m => m.Name)
                });

            // Build the output XML
            var xmlMonasteries = new XElement("monasteries");
            foreach (var country in countriesQuery)
            {
                var xmlCountry = new XElement("country");
                xmlCountry.Add(new XAttribute("name", country.CountryName));

                foreach (var monastery in country.Monasteries)
                {
                    xmlCountry.Add(new XElement("monastery", monastery));
                }

                xmlMonasteries.Add(xmlCountry);
            }
            Console.WriteLine(xmlMonasteries);

            var xmlDoc = new XDocument(xmlMonasteries);
            xmlDoc.Save(@"..\..\monasteries.xml");
        }
 public void FixSize(XNamespace ab, XElement role, string name, string size)
 {
     foreach (var local in role.Elements(ab + "LocalResources"))
         foreach (var storage in local.Elements(ab + "LocalStorage"))
             if (storage.Attribute("name").Value == name)
                 storage.SetAttributeValue("sizeInMB", size);
 }
Пример #30
0
        public DataSafe(string path, string name)
        {
            Ints = new IntGetter(this);
            Longs = new LongGetter(this);
            Bools = new BoolGetter(this);
            Strings = new StringGetter(this);
            Doubles = new DoubleGetter(this);

            path = path + Path.DirectorySeparatorChar + name;
            if(!path.EndsWith(".xml",true,System.Globalization.CultureInfo.CurrentCulture))
                path +=".xml";

            this.path = path;
            this.names = new HashSet<string>();
            if (!File.Exists(path))
            {
                data = new XElement(name);
                data.Save(path);
            }
            else
            {
                data = XElement.Load(path);
                foreach (XElement elem in data.Descendants())
                {
                    names.Add(elem.Name.ToString());
                }
            }
        }