当前位置: 首页>>代码示例>>C#>>正文


C# XElement.SetAttributeValue方法代码示例

本文整理汇总了C#中System.Xml.Linq.XElement.SetAttributeValue方法的典型用法代码示例。如果您正苦于以下问题:C# XElement.SetAttributeValue方法的具体用法?C# XElement.SetAttributeValue怎么用?C# XElement.SetAttributeValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Xml.Linq.XElement的用法示例。


在下文中一共展示了XElement.SetAttributeValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ExportGamesToXml

        private static void ExportGamesToXml(IEnumerable<FinishedGame> games)
        {
            var doc = new XDocument();
            var rootNode = new XElement("games");
            doc.Add(rootNode);
            foreach (var game in games)
            {
                var gameNode = new XElement("game");
                gameNode.SetAttributeValue("name", game.Name);
                if (game.Duration != null)
                {
                    gameNode.SetAttributeValue("duration", game.Duration);
                }

                var usersNode = new XElement("users");
                gameNode.Add(usersNode);

                foreach (var user in game.Users)
                {
                    var userNode = new XElement("user");
                    userNode.SetAttributeValue("username", user.Username);
                    userNode.SetAttributeValue("ip-address", user.IpAddress);
                    usersNode.Add(userNode);
                }

                rootNode.Add(gameNode);
            }

            doc.Save(ExportPath + Filename);
            Console.WriteLine("File path: {0}", Path.GetFullPath(ExportPath + Filename));
        }
开发者ID:nok32,项目名称:SoftUni,代码行数:31,代码来源:FinishedGamesMain.cs

示例2: Generate

        public static void Generate()
        {
            using (var db = new SalesContext())
            {
                var sales = new XElement("sales");

                foreach (var supermarket in db.Supermarkets)
                {
                    var sale = new XElement("sale");
                    sale.SetAttributeValue("vendor", supermarket.Name);

                    var records = db.Records
                        .Where(x => x.Supermarket.Id == supermarket.Id)
                        .GroupBy(x => x.Date)
                        .OrderBy(x => x.Key)
                        .Select(x => new { Date = x.Key, Sum = x.Sum(y => y.Quantity * y.UnitPrice) });

                    foreach (var record in records)
                    {
                        var summary = new XElement("summary");

                        summary.SetAttributeValue("date", record.Date.ToShortDateString());
                        summary.SetAttributeValue("total-sum", record.Sum.ToString("00"));

                        sale.Add(summary);
                    }

                    sales.Add(sale);
                }

                sales.Save(FilePath);
                //Console.WriteLine(File.ReadAllText(FilePath));
            }
        }
开发者ID:aleks-todorov,项目名称:HomeWorks,代码行数:34,代码来源:SalesReportsByVendors.cs

示例3: GetData

 public XElement GetData()
 {
     XElement data = new XElement(XMLName);
     data.SetAttributeValue("Name", Name);
     data.SetAttributeValue("Type", Type);
     return data;
 }
开发者ID:EPecherkin,项目名称:UMLLibrary,代码行数:7,代码来源:ObjectListItem.cs

示例4: HandleTarget

        private void HandleTarget(BSharpBuilderWriteTarget target) {
            foreach (var bsClass in target.Entity.Elements()) {
                var bSharpClass = new XElement(BSharpBuilderDefaults.BSharpClassContainerName);
                var bSharpIndexSet = new XElement(
                    BSharpBuilderDefaults.DefaultClassIndexContainerName,
                    bSharpClass
                );

                var writeTarget = new BSharpBuilderWriteTarget {
                    Directory = Project.GetOutputDirectory(),
                    Entity = bSharpIndexSet,
                    EntityContainerName = BSharpBuilderDefaults.DefaultClassIndexContainerName,
                    Extension = BSharpBuilderDefaults.IndexFileExtension,
                    Filename = BSharpBuilderDefaults.IndexFileName,
                    MergeIfExists = true
                };

                WriteIndexAttributeIfExists(bSharpClass, bsClass,BSharpSyntax.ClassNameAttribute);
                WriteIndexAttributeIfExists(bSharpClass, bsClass, BSharpSyntax.ClassPrototypeAttribute);
                WriteIndexAttributeIfExists(bSharpClass, bsClass, BSharpSyntax.ClassRuntimeAttribute);

                bSharpClass.SetAttributeValue("file", target.Path.Remove(0, Project.GetOutputDirectory().Length).Replace("\\","/"));
				if (bsClass.Attribute(BSharpSyntax.ClassFullNameAttribute) != null)
				{
					bSharpClass.SetAttributeValue(BSharpSyntax.Namespace, BSharpBuilderClassUtils.GetNamespace(bsClass.Attribute(BSharpSyntax.ClassFullNameAttribute).Value));
                }

                WriteManager.Add(writeTarget);
            }
        }
开发者ID:Qorpent,项目名称:qorpent.sys,代码行数:30,代码来源:GenerateIndexTask.cs

示例5: CreateXDT

        private string CreateXDT(BuildConfig config)
        {
            XNamespace xdt = "http://schemas.microsoft.com/XML-Document-Transform";

            var doc = XDocument.Parse("<?xml version=\"1.0\"?><configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\"></configuration>");

            var connectionStrings = new XElement(XName.Get("connectionStrings"));
            doc.Root.Add(connectionStrings);
            foreach (var item in config.ConnectionStrings)
            {
                XElement cnstr = new XElement(XName.Get("add"));
                connectionStrings.Add(cnstr);
                cnstr.SetAttributeValue(XName.Get("name"), item.Name);
                cnstr.SetAttributeValue(XName.Get("connectionString"), item.ConnectionString);
                cnstr.SetAttributeValue(xdt + "Transform", "SetAttributes");
                cnstr.SetAttributeValue(xdt + "Locator", "Match(name)");
                if(item.ProviderName!=null){
                    cnstr.SetAttributeValue(XName.Get("providerName"), item.ProviderName);
                }
            }
            var appSettings = new XElement(XName.Get("appSettings"));
            doc.Root.Add(appSettings);
            foreach (var item in config.AppSettings)
            {
                XElement cnstr = new XElement(XName.Get("add"));
                appSettings.Add(cnstr);
                cnstr.SetAttributeValue(XName.Get("key"), item.Key);
                cnstr.SetAttributeValue(XName.Get("value"), item.Value);
                cnstr.SetAttributeValue(xdt + "Transform", "SetAttributes");
                cnstr.SetAttributeValue(xdt + "Locator", "Match(key)");
            }

            return doc.ToString(SaveOptions.OmitDuplicateNamespaces);
        }
开发者ID:neurospeech,项目名称:iis-ci,代码行数:34,代码来源:XDTService.cs

示例6: DumpAssembly

        public static XElement DumpAssembly(string assemblyFile, bool includeParentMemebers=false)
        {
            AssemblyDefinition source = AssemblyDefinition.ReadAssembly(assemblyFile);

            if (source == null)
            {
                return null;
            }

            List<TypeDefinition> sourceTypes;

            try
            {
                sourceTypes = source.Modules.SelectMany(m => m.Types).Where(t => t.IsPublic).ToList();
                (source.MainModule.AssemblyResolver as DefaultAssemblyResolver).AddSearchDirectory(Path.GetDirectoryName(assemblyFile));
                sourceTypes.AddRange(source.Modules.SelectMany(m => m.ExportedTypes).Select(r => r.Resolve()).Where(t => t.IsPublic));
            }
            catch (Exception)
            {
                //we don't care about broken or empty files
                return null;
            }

            XElement asmXml = new XElement("Assembly");

            asmXml.SetAttributeValue("Name", source.Name.Name);
            asmXml.SetAttributeValue("Info", source.FullName);

            foreach (TypeDefinition typeDefinition in sourceTypes)
            {
                asmXml.Add(DumpType(typeDefinition, includeParentMemebers));
            }

            return asmXml;
        }
开发者ID:vlad-zapp,项目名称:AssemblyChecker,代码行数:35,代码来源:Dump.cs

示例7: FeatureActivated

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                // Add the Mobile Web Part Adapter to the compat.browser file
                SPWebApplication webApp = null;

                if (properties.Feature.Parent is SPSite)
                {
                    SPSite spSite = properties.Feature.Parent as SPSite;
                    webApp = spSite.WebApplication;
                }
                else if (properties.Feature.Parent is SPWebApplication)
                {
                    webApp = properties.Feature.Parent as SPWebApplication;
                }

                String pathToCompatBrowser = webApp.IisSettings[SPUrlZone.Default].Path + @"\App_Browsers\compat.browser";
                XElement compatBrowser = XElement.Load(pathToCompatBrowser);

                // Get the node for the default browser.
                XElement controlAdapters = compatBrowser.XPathSelectElement("./browser[@refID = \"default\"]/controlAdapters");

                // Create and add the markup.
                XElement newAdapter = new XElement("adapter");

                newAdapter.SetAttributeValue("controlType", controlType);
                newAdapter.SetAttributeValue("adapterType", webPartFQN);

                controlAdapters.Add(newAdapter);
                compatBrowser.Save(pathToCompatBrowser);
            }
            catch { }
        }
开发者ID:nschonni,项目名称:wet-boew-sharepoint,代码行数:34,代码来源:AttachAdapter.EventReceiver.cs

示例8: RemainingQuantities

        /// <summary>
        /// Exports to XML all remaining products and the shops they are located in
        /// </summary>
        /// <param name="db"></param>
        public static void RemainingQuantities()
        {
            //create root element and database
            var db = new SQLServerContextFactory().Create();
            XElement root = new XElement("products");

            //make a collection with all the data you want to export to XML. Use as many joins as needed
            var products = db.Products.OrderBy(p => p.QuantityInStock);

            //go through all items in the collection
            foreach (var product in products)
            {
                //for every nested element you must create new instance of XElement
                XElement currentProduct = new XElement("product"); //create tag
                currentProduct.SetAttributeValue("name", product.Name); //set attribute
                currentProduct.SetAttributeValue("description", product.Description); //set another attribute

                XElement productInfo = new XElement("info"); //nest element after "Product"
                productInfo.Add(new XElement("price", product.Price)); //add element inside "Info"
                //you can create those as new XElement like the creation of "Info"
                productInfo.Add(new XElement("quantity", product.QuantityInStock));

                //add info to product
                currentProduct.Add(productInfo);

                //add current set of tags to root
                root.Add(currentProduct);
            }

            string methodName = MethodBase.GetCurrentMethod().Name;
            root.Save(Helpers.NamingFactory.BuildName(methodName, fileType));
        }
开发者ID:freemsly,项目名称:Databases-Course-Teamwork,代码行数:36,代码来源:XMLExporter.cs

示例9: Write

        public void Write(Project project)
        {
            var file = Path.Combine(project.Directory, PackagesConfig);
            XElement document;
            if (_fileSystem.FileExists(file))
            {
                document = XElement.Load(file);
                document.RemoveAll();
            }
            else
            {
                document = new XElement("packages");
            }


            project.Dependencies.Each(x =>
            {
                var package = new XElement("package");
                package.SetAttributeValue("id", x.Name);

                // TODO -- Make this easier to query
                var solutionLevel = project.Solution.Dependencies.Find(x.Name);
                package.SetAttributeValue("version", solutionLevel.Version.ToString());

                // TODO -- Probably shouldn't hardcode this...
                package.SetAttributeValue("targetFramework", "net40");

                document.Add(package);
            });

            document.Save(file);
        }
开发者ID:modulexcite,项目名称:ripple,代码行数:32,代码来源:NuGetDependencyStrategy.cs

示例10: GetPlaceResultForMobile

        public static ICollection<XElement> GetPlaceResultForMobile(Mobile.Server.Transaction transaction, Token token)
        {
            ICollection<XElement> elements = new List<XElement>();
            if (token != null && token.AppType == AppType.Mobile)
            {
                Token placeToken = new Token(token.UserID, token.UserType, AppType.TradingConsole);
                string tranCode;
                TransactionError error = Application.Default.TradingConsoleServer.Place(placeToken, Application.Default.StateServer, transaction.ToXmlNode(), out tranCode);
                if (error == TransactionError.Action_ShouldAutoFill)
                {
                    error = TransactionError.OK;
                }

                foreach (Mobile.Server.Order order in transaction.Orders)
                {
                    XElement orderErrorElement = new XElement("Order");
                    orderErrorElement.SetAttributeValue("Id", order.Id);
                    orderErrorElement.SetAttributeValue("ErrorCode", error.ToString());
                    elements.Add(orderErrorElement);
                }

                Mobile.Manager.UpdateWorkingOrder(token, transaction.Id, error);
                return elements;
            }
            return null;
        }
开发者ID:RobertHu,项目名称:-NewTraderServer,代码行数:26,代码来源:MobileHelper.cs

示例11: ProjectOpened

        public static void ProjectOpened(Project project)
        {
            XDocument document;
            if (!File.Exists(Path.Combine(MainWindow.UserPath, "Settings", "recent.xml")))
            {
                document = new XDocument();
                document.Add(new XElement("projects"));
            }
            else
                document = XDocument.Load(Path.Combine(MainWindow.UserPath, "Settings", "recent.xml"));
            var newProject = new XElement("project");
            newProject.SetAttributeValue("config", project.File);
            newProject.SetAttributeValue("name", project.Name);

            XElement toRemove = null;
            foreach (var element in document.Root.Elements())
            {
                if (element.Attribute("config").Value == newProject.Attribute("config").Value)
                {
                    toRemove = element;
                    break;
                }
            }
            if (toRemove != null)
                toRemove.Remove();

            document.Root.AddFirst(newProject);
            if (document.Root.Elements().Count() > 10)
            {
                var elements = document.Root.Elements().Take(10);
                document.Root.RemoveAll();
                document.Root.Add(elements);
            }
            document.Save(Path.Combine(MainWindow.UserPath, "Settings", "recent.xml"));
        }
开发者ID:SirCmpwn,项目名称:Halibut,代码行数:35,代码来源:RecentProjects.cs

示例12: SaveBundleFromViewModel

        public static void SaveBundleFromViewModel(BundleViewModel bundle, string bundleType)
        {
            var doc = XDocument.Load(HttpContext.Current.Server.MapPath(Config.BundlesConfigPath));

            var bundleEl = new XElement(bundleType + "Bundle");

            if (doc.Descendants(bundleType + "Bundle").Any(x => x.Attribute("virtualPath").Value == bundle.VirtualPath))
                bundleEl =
                    doc.Descendants(bundleType + "Bundle")
                       .Single(x => x.Attribute("virtualPath").Value == bundle.VirtualPath);
            else
            {

                bundleEl.SetAttributeValue("virtualPath", bundle.VirtualPath);
                doc.Descendants("bundles").Single().Add(bundleEl);
            }

            bundleEl.SetAttributeValue("disableMinification", bundle.DisableMinification.ToString());

            bundleEl.Elements().Remove();

            if (bundle.Files != null)
            {
                foreach (var file in bundle.Files)
                {
                    var includeEl = new XElement("include");
                    includeEl.SetAttributeValue("virtualPath", file);
                    bundleEl.Add(includeEl);
                }
            }

            doc.Save(HttpContext.Current.Server.MapPath(Config.BundlesConfigPath));

            HttpRuntime.UnloadAppDomain();
        }
开发者ID:Jeavon,项目名称:BundlingAndMinificationForTheMasses,代码行数:35,代码来源:Bundles.cs

示例13: Generate

        public XElement Generate(TestCase testCase)
        {
            XElement main = new XElement("div");

            XElement tr = new XElement("tr");
            XElement tdName = new XElement("td", testCase.Desription);
            XElement tdStatus = new XElement("td", testCase.Result);
            XElement tdTime = new XElement("td", testCase.Time);

            XElement trMessage = new XElement("tr");
            XElement tdMessage = new XElement("td");


            if (testCase.Message != null || testCase.StackTrace != null)
            {
                XElement preMessage = new XElement("pre", testCase.Message);
                XElement preStackTrace = new XElement("pre", testCase.StackTrace);
                tdMessage.SetValue("MESSAGE:\n");

                tdMessage.Add(preMessage);
                tdMessage.Add(preStackTrace);
                trMessage.Add(tdMessage);
            }
            else if (!string.IsNullOrEmpty(testCase.Reason))
            {
                XElement reasonMessage = new XElement("pre", testCase.Reason);
                tdMessage.Add(reasonMessage);
                trMessage.Add(tdMessage);
            }

            tr.Add(tdName);
            tr.Add(tdStatus);
            tr.Add(tdTime);

            main.Add(tr);
            main.Add(trMessage);

            tdName.SetAttributeValue("style", "text-align:left;");
            trMessage.SetAttributeValue("style", "font-size:11px; text-align:left;");
            trMessage.SetAttributeValue("bgcolor", "lightgrey");
            tdMessage.SetAttributeValue("colspan", "3");


            switch (testCase.Result)
            {
                case "Success":
                    tdStatus.SetAttributeValue("bgcolor", "green");
                    break;
                case "Ignored":
                    tdStatus.SetAttributeValue("bgcolor", "yellow");
                    break;
                case "Failure":
                    tdStatus.SetAttributeValue("bgcolor", "red");
                    break;
                default:
                    break;
            }

            return main;
        }
开发者ID:IIITanbI,项目名称:OnlinerTests,代码行数:60,代码来源:Program.cs

示例14: CreateXml

        public static void CreateXml(string filePath)
        {
            using (SupermarketDBContext sqldb = new SupermarketDBContext())
            {
                string format = "dd-MMM-yyyy";

                XElement sales = new XElement("sales");
                foreach (var vendor in sqldb.Vendors.ToList().Where(
                    x=> x.Products.Any(y => y.SalesReports.Count > 0)))
                {
                    XElement elSale = new XElement("sale");
                    elSale.SetAttributeValue("vendor", vendor.VendorName.ToString());
                    foreach (var product in vendor.Products.ToList())
                    {
                        foreach (var report in product.SalesReports.ToList())
                        {
                            XElement summary = new XElement("summary");
                            summary.SetAttributeValue("date", report.ReportDate.ToString(format));
                            summary.SetAttributeValue("total-sum", report.Sum.ToString());
                            elSale.Add(summary);
                        }
                    }

                    sales.Add(elSale);
                }
                sales.Save(filePath);
            }
        }
开发者ID:kirotab,项目名称:ReportsDBTeam,代码行数:28,代码来源:Supermarkt.Utils.Xml.cs

示例15: UpdateVs2010Compatibility

        void UpdateVs2010Compatibility(XDocument document, string file) {
            var elements = document.Descendants().Where(element 
                => element.Name.LocalName == "VSToolsPath" || element.Name.LocalName == "VisualStudioVersion" );
            var xElements = elements as XElement[] ?? elements.ToArray();
            bool save=xElements.Any();
            xElements.Remove();


            elements=document.Descendants().Where(element 
                => element.Name.LocalName == "Import" &&
                (element.Attribute("Project").Value.StartsWith("$(MSBuildExtensionsPath)")||
                element.Attribute("Project").Value.StartsWith("$(MSBuildExtensionsPath32)")));
            var enumerable = elements as XElement[] ?? elements.ToArray();
            if (!save)
                save = enumerable.Any();

            if (IsWeb(document, GetOutputType(document))&& !document.Descendants().Any(element =>
                element.Name.LocalName == "Import" && element.Attribute("Project").Value.StartsWith("$(VSToolsPath)")&&
                element.Attribute("Condition").Value.StartsWith("'$(VSToolsPath)' != ''"))) {
                var element = new XElement(_xNamespace+"Import");
                element.SetAttributeValue("Project",@"$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets");
                element.SetAttributeValue("Condition", @"'$(VSToolsPath)' != ''");
                Debug.Assert(document.Root != null, "document.Root != null");
                document.Root.Add(element);
                save = true;
            }
            
            enumerable.Remove();

            if (save)
                DocumentHelper.Save(document, file);
        }
开发者ID:kamchung322,项目名称:eXpand,代码行数:32,代码来源:ProjectUpdater.cs


注:本文中的System.Xml.Linq.XElement.SetAttributeValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。