• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Linq.XDocument类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Xml.Linq.XDocument的典型用法代码示例。如果您正苦于以下问题:C# XDocument类的具体用法?C# XDocument怎么用?C# XDocument使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



XDocument类属于System.Xml.Linq命名空间,在下文中一共展示了XDocument类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetXml

        public string GetXml(bool validate)
        {
            XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en";

            var spectrum_licences = getLicences();

            XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences));

            foreach (XElement e in doc.Root.DescendantsAndSelf())
            {
                if (e.Name.Namespace == "")
                    e.Name = ns + e.Name.LocalName;
            }

            var errors = new StringBuilder();

            if (validate)
            {
                XmlSchemaSet set = new XmlSchemaSet();
                var schema = getMainSchema();
                set.Add(null, schema);

                doc.Validate(set, (sender, args) => { errors.AppendLine(args.Message); });
            }

            //return errors.Length > 0 ? errors.ToString() : doc.ToString();
            var  result = errors.Length > 0 ? "Validation Errors: " + errors.ToString() : getDocumentAsString(doc);
            return result;
        }
开发者ID:mathewvance,项目名称:Silo,代码行数:29,代码来源:SldrTechnicalDataService.cs


示例2: ImportTexturesFromXml

        private void ImportTexturesFromXml(XDocument xml)
        {
            var texData = xml.Root.Elements("ImportTexture");
            foreach (var tex in texData)
            {
                string name = tex.Attribute("filename").Value;
                string data = tex.Value;

                // The data is gzip compressed base64 string. We need the raw bytes.
                //byte[] bytes = ImportUtils.GzipBase64ToBytes(data);
                byte[] bytes = ImportUtils.Base64ToBytes(data);

                // Save and import the texture asset
                {
                    string pathToSave = GetTextureAssetPath(name);
                    ImportUtils.ReadyToWrite(pathToSave);
                    File.WriteAllBytes(pathToSave, bytes);
                    AssetDatabase.ImportAsset(pathToSave, ImportAssetOptions.ForceSynchronousImport);
                }

                // Create a material if needed in prepartion for the texture being successfully imported
                {
                    string materialPath = GetMaterialAssetPath(name);
                    Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
                    if (material == null)
                    {
                        // We need to create the material afterall
                        // Use our custom shader
                        material = new Material(Shader.Find("Tiled/TextureTintSnap"));
                        ImportUtils.ReadyToWrite(materialPath);
                        AssetDatabase.CreateAsset(material, materialPath);
                    }
                }
            }
        }
开发者ID:krislerv,项目名称:Unity-Game,代码行数:35,代码来源:ImportTiled2Unity.Xml.cs


示例3: VersionedModel

        public VersionedModel(XDocument model, string version = null)
        {
            DebugCheck.NotNull(model);

            _model = model;
            _version = version;
        }
开发者ID:Cireson,项目名称:EntityFramework6,代码行数:7,代码来源:VersionedModel.cs


示例4: GetXDocument

 public static XDocument GetXDocument(this OpenXmlPart part)
 {
     try
     {
         XDocument partXDocument = part.Annotation<XDocument>();
         if (partXDocument != null)
             return partXDocument;
         using (Stream partStream = part.GetStream())
         {
             if (partStream.Length == 0)
             {
                 partXDocument = new XDocument();
                 partXDocument.Declaration = new XDeclaration("1.0", "UTF-8", "yes");
             }
             else
                 using (XmlReader partXmlReader = XmlReader.Create(partStream))
                     partXDocument = XDocument.Load(partXmlReader);
         }
         part.AddAnnotation(partXDocument);
         return partXDocument;
     }
     catch (Exception e)
     {
         throw e;
     }
 }
开发者ID:BogdanDamianC,项目名称:Open-Xml-PowerTools,代码行数:26,代码来源:PtOpenXmlUtil.cs


示例5: LessonParse

 //Возвращает список предметов
 public static string[] LessonParse(XDocument Lessons, string Class)
 {
     string[] New = new string[0];
       foreach (string Lesson in Lessons.Element("Lessons").Elements(Class).Elements("LessIds"))
     New = HelpDeriver(Lesson);
       return New;
 }
开发者ID:Mexahoid,项目名称:CSF,代码行数:8,代码来源:ParseLessons.cs


示例6: DelParse

 //Возвращает список текстов класса если DataType = text и дат если date
 public static List<string> DelParse(XDocument Lessons, string Class, string LessonType, string DataType)
 {
     List<string> Data = new List<string>();
       foreach (string Text in Lessons.Descendants(Class).Elements(LessonType).Elements(DataType)) //Можно получить Class и lesson
     Data.Add(TextDeriver(Text));  //Мы получаем одну строку, поэтому однострочный дерайвер
       return Data;
 }
开发者ID:Mexahoid,项目名称:CSF,代码行数:8,代码来源:ParseLessons.cs


示例7: GetIsSilverlight

 static bool GetIsSilverlight(XDocument xDocument)
 {
     var targetFrameworkIdentifier = xDocument.BuildDescendants("TargetFrameworkIdentifier")
         .Select(c => c.Value)
         .FirstOrDefault();
     return (string.Equals(targetFrameworkIdentifier, "Silverlight", StringComparison.OrdinalIgnoreCase));
 }
开发者ID:Z731,项目名称:NotifyPropertyWeaver,代码行数:7,代码来源:FrameworkTypeReader.cs


示例8: LastFMTrackInfo

    public LastFMTrackInfo(XDocument xDoc)
    {
      if (xDoc.Root == null) return;
      var track = xDoc.Root.Element("track");
      if (track == null) return;

      Identifier = (int) track.Element("id");
      TrackTitle = (string) track.Element("name");
      MusicBrainzId = (string) track.Element("mbid");
      TrackURL = (string) track.Element("url");
      Duration = (int) track.Element("duration");
      Listeners = (int) track.Element("listeners");
      Playcount = (int) track.Element("playcount");

      var artistElement = track.Element("artist");
      if (artistElement != null) ArtistName = (string) artistElement.Element("name");

      TopTags = (from tagElement in track.Descendants("tag")
                 let tagName = (string) tagElement.Element("name")
                 let tagURL = (string) tagElement.Element("url")
                 select new LastFMTag(tagName, tagURL)
                ).ToList();

      var albumElement = track.Element("album");
      if (albumElement != null)
      {
        Images = (from i in albumElement.Elements("image")
                  select new LastFMImage(
                    LastFMImage.GetImageSizeEnum((string) i.Attribute("size")),
                    (string) i
                    )
                 ).ToList();
      }
    }
开发者ID:arangas,项目名称:MediaPortal-1,代码行数:34,代码来源:LastFMTrack.cs


示例9: GetReferences

        private static IEnumerable<ReferenceDescriptor> GetReferences(XDocument document) {
            var assemblyReferences = document
                .Elements(ns("Project"))
                .Elements(ns("ItemGroup"))
                .Elements(ns("Reference"))
                .Where(c => c.Attribute("Include") != null)
                .Select(c => {
                            string path = null;
                            XElement attribute = c.Elements(ns("HintPath")).FirstOrDefault();
                            if (attribute != null) {
                                path = attribute.Value;
                            }

                            return new ReferenceDescriptor {
                                SimpleName = ExtractAssemblyName(c.Attribute("Include").Value),
                                FullName = c.Attribute("Include").Value,
                                Path = path,
                                ReferenceType = ReferenceType.Library
                            };
                        });

            var projectReferences = document
                .Elements(ns("Project"))
                .Elements(ns("ItemGroup"))
                .Elements(ns("ProjectReference"))
                .Attributes("Include")
                .Select(c => new ReferenceDescriptor {
                    SimpleName = Path.GetFileNameWithoutExtension(c.Value),
                    FullName = Path.GetFileNameWithoutExtension(c.Value),
                    Path = c.Value,
                    ReferenceType = ReferenceType.Project
                });

            return assemblyReferences.Union(projectReferences);
        }
开发者ID:Vinna,项目名称:DeepInSummer,代码行数:35,代码来源:DefaultProjectFileParser.cs


示例10: GetXDocument

 public XDocument GetXDocument()
 {
     List<PortSetting> list = new List<PortSetting>()
     {
         new PortSetting()
         {
             Name ="InputPort",
             Value=""
         },
         new PortSetting()
         {
             Name ="OutputPort",
             Value=""
         },
     };
   
     XDocument xDoc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XComment("System Setting"),
                new XElement("Settings",
                    list.Select(x => (new XElement("Setting",
                                          new XElement("Name", x.Name),
                                          new XElement("Value", x.Value))))
              ));
     return xDoc;
 }
开发者ID:haltt051093,项目名称:IMS-datacenter,代码行数:26,代码来源:PortSettingDBSeeder.cs


示例11: XmlLoggerBasicTest

        public void XmlLoggerBasicTest()
        {
            var path = @"x:\deployments\1234\log.xml";
            var fileSystem = new Mock<IFileSystem>();
            var file = new Mock<FileBase>();
            var id = Guid.NewGuid().ToString();
            var message = Guid.NewGuid().ToString();
            var doc = new XDocument(new XElement("entries", 
                new XElement("entry",
                    new XAttribute("time", "2013-12-08T01:58:24.0247841Z"),
                    new XAttribute("id", id),
                    new XAttribute("type", "0"),
                    new XElement("message", message)
                )
            ));
            var mem = new MemoryStream();
            doc.Save(mem);

            // Setup
            fileSystem.SetupGet(f => f.File)
                      .Returns(file.Object);
            file.Setup(f => f.Exists(path))
                .Returns(true);
            file.Setup(f => f.OpenRead(path))
                .Returns(() => { mem.Position = 0; return mem; });

            // Test
            var logger = new XmlLogger(fileSystem.Object, path, Mock.Of<IAnalytics>());
            var entries = logger.GetLogEntries();

            // Assert
            Assert.Equal(1, entries.Count());
            Assert.Equal(id, entries.First().Id);
            Assert.Equal(message, entries.First().Message);
        }
开发者ID:hackmp,项目名称:kudu,代码行数:35,代码来源:XmlLoggerFacts.cs


示例12: Save

        public static void Save(string path)
        {
            var document = new XDocument();
            var root = new XElement("PrettyCheckoutDatabase", new XAttribute("Version", DataReaderFileVersion));

            foreach (var product in Program.Environment.Products)
            {
                var element = new XElement("Product");
                element.Add(new XAttribute("ID", product.Index));
                element.Add(new XAttribute("Name", product.Name));
                element.Add(new XAttribute("Price", product.Price));
                element.Add(new XAttribute("PriceN", product.PriceN));
                element.Add(new XAttribute("Vat", product.Vat));
                element.Add(new XElement("Description", new XCData(product.Description == null ? string.Empty : product.Description)));

                root.Add(element);
            }

            document.Add(root);

            try
            {
                document.Save(path);
            }
            catch (Exception)
            {
                MessageBox.Show("Data file could not be saved - " + path);
            }
        }
开发者ID:MadnessFreak,项目名称:PrettyCheckout,代码行数:29,代码来源:DataReader.cs


示例13: WriteProcessed

		/// <summary>
		/// Writes the results of XSLT transformation into the specified TextWriter.
		/// </summary>
		public static void WriteProcessed(string templateName, XsltArgumentList argumentList, XDocument data, TextWriter outStream)
		{
			using (XmlReader reader = data.CreateReader())
			{
				GetCompiledTransform(templateName).Transform(reader, argumentList, outStream);
			}
		}
开发者ID:shuruev,项目名称:CCNet.Extensions,代码行数:10,代码来源:TemplateEngine.cs


示例14: GetCertificate

        public static X509Certificate2 GetCertificate(XDocument xdoc)
        {
            var profile = xdoc.Descendants("PublishProfile").Single();
            var managementCertbase64String = profile.Attribute("ManagementCertificate").Value;

            return new X509Certificate2(Convert.FromBase64String(managementCertbase64String));
        }
开发者ID:EmiiFont,项目名称:Azureoid,代码行数:7,代码来源:AssetManagement.cs


示例15: GenerateXML

 private XDocument GenerateXML()
 {
     XDocument xml = new XDocument(
         new XDeclaration("1.0", "windows-1250", "true"),
         new XElement("Zadost",
             new XAttribute("Verze", "01"),
             new XAttribute("Kod", this.smlouvaID),
             new XAttribute("Typ", "Z"),
             new XAttribute("Timestamp", this.smlouvaCreateDate.ToString()),
             new XElement("NazevFilmu", tbNazevFilmu.Text),
             new XElement("NazevSkladby", tbNazevSkladby.Text),
             new XElement("AutoriHudby", tbAutoriHudby.Text),
             new XElement("AutoriTextu", tbAutoriTextu.Text),
             new XElement("Nakladatel", tbNakladatel.Text),
             new XElement("Label", tbLabel.Text),
             new XElement("ZpracovatelHudby", tbZpracovatelHudby.Text),
             new XElement("Subtextar", tbSubtextar.Text),
             new XElement("VyrobceReklamnihoSpotu", tbVyrobceReklamy.Text),
             new XElement("Zadavatel", tbZadavatel.Text),
             new XElement("HudebniStopaz", tbHudebniStopaz.Text),
             new XElement("DruhUziti", tbDruhUziti.Text),
             new XElement("ZpusobUziti", tbZpusobUziti.Text),
             new XElement("SouhlasUdelil", tbSouhlasUdelil.Text),
             new XElement("DobaTrvaniLicence", tbDobaTrvaniLicence.Text),
             new XElement("Poznamky", tbPoznamka.Text),
             new XElement("EmailProPotvrzeni", tbEmailProPotvrzeni.Text)
                     ));
     return xml;
 }
开发者ID:mpopek,项目名称:PublicWebForms,代码行数:29,代码来源:OznameniOUdeleniSouhlasu.aspx.cs


示例16: RSS

        public ContentResult RSS()
        {
            List<Post> posts = Post.Collection.Find(Post.ActiveScope)
                .SetSortOrder(Post.DefaultSortByScope)
                .ToList();

            var rss = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("rss",
                  new XAttribute("version", "2.0"),
                        new XElement("channel",
                          new XElement("title", AppSettings.RSSTitle),
                          new XElement("link", AppSettings.RSSLink),
                          new XElement("description", AppSettings.RSSDescription),
                          new XElement("copyright", AppSettings.RSSCopyright),
                        from p in posts
                        select
                        new XElement("item",
                              new XElement("title", p.Title),
                              new XElement("description", p.Description),
                              new XElement("link", String.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated)),
                              new XElement("pubDate", p.PublishedOn.ToString("R")),
                              new XElement("guid", String.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated))
                              )
                          )
                     )
                );

            return Content(rss.ToString(), "text/xml");
        }
开发者ID:beardeddev,项目名称:briar,代码行数:29,代码来源:UtilityController.cs


示例17: SiteMap

        public ContentResult SiteMap()
        {
            List<Page> pages = Page.Collection.Find(Page.ActiveScope).ToList();
            List<Post> posts = Post.Collection.Find(Post.ActiveScope)
                .SetSortOrder(Post.DefaultSortByScope)
                .ToList();

            var sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                new XElement(AppSettings.SiteMapNamespace + "urlset",
                        from p in pages
                        select
                          new XElement(AppSettings.SiteMapNamespace + "url",
                            new XElement(AppSettings.SiteMapNamespace + "loc", string.Format(AppSettings.PageUrlFormat, Request.Url.Host, p.Url)),
                                new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", p.UpdatedOn))
                                ),
                            new XElement("changefreq", "monthly"),
                            new XElement("priority", "0.5"),
                        from p in posts
                        select
                            new XElement(AppSettings.SiteMapNamespace + "url",
                            new XElement(AppSettings.SiteMapNamespace + "loc", string.Format(AppSettings.PostUrlFormat, Request.Url.Host, p.TitleTransliterated)),
                                new XElement("lastmod", String.Format("{0:yyyy-MM-dd}", p.UpdatedOn))
                                ),
                            new XElement("changefreq", "monthly"),
                            new XElement("priority", "0.5")
                        )
                );

            return Content(sitemap.ToString(), "text/xml");
        }
开发者ID:beardeddev,项目名称:briar,代码行数:30,代码来源:UtilityController.cs


示例18: SiteMap

        public ActionResult SiteMap()
        {
            var _Pages = PageService.GetSitemap(APP._SiteID, Request.Url.Authority);
            XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
            var _Q = from i in _Pages.Pages
                     select
                     new XElement(ns + "url",
                         new XElement(ns + "loc", Request.Url.Scheme + "://" + Request.Url.Authority + "/" + i.FriendlyUrl)
                         , new XElement(ns + "changefreq", "always"));

            if (_Pages.Blog)
            {
                _Q = _Q.Union((from i in _Pages.Posts
                               select
                               new XElement(ns + "url",
                                   new XElement(ns + "loc", Url.Action("detail", "blog", new { BlogPostID = i.BlogPostID, FriendlyUrl = i.FriendlyUrl }, Request.Url.Scheme))
                                   , new XElement(ns + "changefreq", "always"))))
                                   .Union((from i in _Pages.BlogCategories
                                           select
                                           new XElement(ns + "url",
                                               new XElement(ns + "loc", Url.Action("index", "blog", new { BlogCategoryFriendlyUrl = i.FriendlyUrl }, Request.Url.Scheme))
                                               , new XElement(ns + "changefreq", "always"))))
                                               .Union((from i in _Pages.BlogTags
                                                       select
                                                       new XElement(ns + "url",
                                                           new XElement(ns + "loc", Url.Action("tag", "blog", new { BlogTagName = i.BlogTagName }, Request.Url.Scheme))
                                                           , new XElement(ns + "changefreq", "always"))));
            }
            var sitemap = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement(ns + "urlset", _Q));
            return Content("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + sitemap.ToString(), "text/xml");
        }
开发者ID:ansarbek,项目名称:thewall9-CMS,代码行数:31,代码来源:PageController.cs


示例19: RetargetWithMetadataConverter

        /// <remarks>Internal for testing.</remarks>
        internal static void RetargetWithMetadataConverter(XDocument xdoc, Version targetSchemaVersion, MetadataConverterDriver converter)
        {
            Debug.Assert(xdoc != null, "xdoc != null");
            Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid target schema version");

            var inputXml = new XmlDocument { PreserveWhitespace = true };
            using (var reader = xdoc.CreateReader())
            {
                inputXml.Load(reader);
            }

            var outputXml = converter.Convert(inputXml, targetSchemaVersion);
            if (outputXml != null)
            {
                // Dev10 Bug 550594: There is a bug in XmlEditor that prevents from deleting the root node
                // unless the root node has previous sibling (like a comment or Xml declaration).
                if (xdoc.Root.PreviousNode == null)
                {
                    xdoc.Root.AddBeforeSelf(new XComment(""));
                }

                // update xml document with new root element
                xdoc.Root.Remove();
                using (var reader = new XmlNodeReader(outputXml))
                {
                    var newDoc = XDocument.Load(reader);
                    xdoc.Add(newDoc.Root);
                }

                // Do not reload artifact here
                // Until the transaction is commited, the XLinq representation of the parsed xml tree hasn't been generated yet.
            }
        }
开发者ID:Cireson,项目名称:EntityFramework6,代码行数:34,代码来源:RetargetXmlNamespaceCommand.cs


示例20: CreateGpx_1_1_Route

        private Route CreateGpx_1_1_Route(XDocument routeDocument, XNamespace ns)
        {
            XElement track = routeDocument.Root.Element(ns + "trk");
            string name = track.Element(ns + "name").Value;

            Route newRoute = new Route {Name = name, DateCreated = DateTime.Now};
            List<RoutePoint> routePoints = new List<RoutePoint>();
            var trackPoints = track.Descendants(ns + "trkpt");
            foreach (XElement trackPoint in trackPoints)
            {
                RoutePoint routePoint = new RoutePoint();
                routePoint.Latitude = double.Parse(trackPoint.Attribute("lat").Value);
                routePoint.Longitude = double.Parse(trackPoint.Attribute("lon").Value);
                routePoint.Elevation = double.Parse(trackPoint.Element(ns + "ele").Value);
                routePoint.TimeRecorded = DateTime.Parse(trackPoint.Element(ns + "time").Value);
                routePoints.Add(routePoint);
            }
            routePoints = routePoints.OrderBy(rp => rp.TimeRecorded).ToList();
            int index = 0;
            foreach (RoutePoint routePoint in routePoints)
            {
                routePoint.SequenceIndex = index;
                index++;
            }
            newRoute.RoutePoints = routePoints;
            newRoute.Distance = CalculateDistance(newRoute.RoutePoints);
            Tuple<double, double> ascentDescent = CalculateAscentDescent(newRoute.RoutePoints);
            newRoute.TotalAscent += ascentDescent.Item1;
            newRoute.TotalDescent += ascentDescent.Item2;
            return newRoute;
        }
开发者ID:JamesRandall,项目名称:CycleCycleCycle.com,代码行数:31,代码来源:GpxRouteCreator.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Linq.XElement类代码示例发布时间:2022-05-26
下一篇:
C# Linq.XDeclaration类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap