C#XML foreach元素?(C# XML foreach element?)

编程入门 行业动态 更新时间:2024-10-12 05:51:53
C#XML foreach元素?(C# XML foreach element?)

我一直在使用C#,并想知道找到每个<lib>标识符的最简单方法是什么,我真的是C#本身的新手,尤其是XML,所以我希望得到一些帮助。

C#

var xmlData = client.DownloadString(figureMapUrl); var doc = XDocument.Parse(xmlData);

XML:

<map> <lib id="myid1" revision="1"> <part id="2732" type="ch"/> <part id="2732" type="ls"/> <part id="2732" type="rs"/> <part id="2733" type="ch"/> </lib> <lib id="myid2" revision="2"> <part id="2732" type="ch"/> <part id="2732" type="ls"/> <part id="2732" type="rs"/> <part id="2733" type="ch"/> </lib> </map>

I have been working with C# and would like to know what the easiest way to find each id of <lib> would be?, I really am new to C# itself and especially XML so I would appreciate some help.

C#

var xmlData = client.DownloadString(figureMapUrl); var doc = XDocument.Parse(xmlData);

XML:

<map> <lib id="myid1" revision="1"> <part id="2732" type="ch"/> <part id="2732" type="ls"/> <part id="2732" type="rs"/> <part id="2733" type="ch"/> </lib> <lib id="myid2" revision="2"> <part id="2732" type="ch"/> <part id="2732" type="ls"/> <part id="2732" type="rs"/> <part id="2733" type="ch"/> </lib> </map>

最满意答案

尝试xml linq

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); var results = doc.Descendants("lib").Select(x => new { id = (string)x.Attribute("id"), revision = (int)x.Attribute("revision"), parts = x.Elements("part").Select(y => new { id = (int)y.Attribute("id"), type = (string)y.Attribute("type") }).ToList() }).ToList(); foreach (string id in results.Select(x => x.id).ToArray()) { } foreach (var part in results.Select(x => x.parts)) { foreach (int id in part.Select(y => y.id).ToArray()) { } } } } }

Try xml linq

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); var results = doc.Descendants("lib").Select(x => new { id = (string)x.Attribute("id"), revision = (int)x.Attribute("revision"), parts = x.Elements("part").Select(y => new { id = (int)y.Attribute("id"), type = (string)y.Attribute("type") }).ToList() }).ToList(); foreach (string id in results.Select(x => x.id).ToArray()) { } foreach (var part in results.Select(x => x.parts)) { foreach (int id in part.Select(y => y.id).ToArray()) { } } } } }

更多推荐

本文发布于:2023-08-04 02:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   XML   foreach   element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!