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()) { } } } } }更多推荐
发布评论