C# 如何查询此结构的xml?
如果我如上所述使用xmlnodelist,那么我如何具体地只获取id=3的元素 或者更有用,如果我可以将所有元素作为元素存储在xnlist中C# 如何查询此结构的xml?,c#,xml,C#,Xml,如果我如上所述使用xmlnodelist,那么我如何具体地只获取id=3的元素 或者更有用,如果我可以将所有元素作为元素存储在xnlist中 XmlNodeList xnList = xmlDoc.SelectNodes("/level1"); 如果你想使用 您甚至可以将XPath和Linq2Xml结合起来 var xDoc = XDocument.Parse(xmlstring); // XDocument.Load(filename) var items = xDoc.Descendant
XmlNodeList xnList = xmlDoc.SelectNodes("/level1");
如果你想使用
您甚至可以将XPath和Linq2Xml结合起来
var xDoc = XDocument.Parse(xmlstring); // XDocument.Load(filename)
var items = xDoc.Descendants("level1")
.First()
.Elements("item")
.Select(item => new {
ID = item.Attribute("id").Value,
Name = item.Attribute("name").Value
})
.ToList();
如果你想使用
您甚至可以将XPath和Linq2Xml结合起来
var xDoc = XDocument.Parse(xmlstring); // XDocument.Load(filename)
var items = xDoc.Descendants("level1")
.First()
.Elements("item")
.Select(item => new {
ID = item.Attribute("id").Value,
Name = item.Attribute("name").Value
})
.ToList();
除了@L.B给出的好答案外,我还使用了Linq,我个人认为它更具可读性:
var item2 = xDoc.XPathSelectElements("//level1/item")
.Select(item => new {
ID = item.Attribute("id").Value,
Name = item.Attribute("name").Value
})
.ToList();
但这完全取决于你的风格 除了@L.B的好答案之外,我还使用Linq,我个人认为它更具可读性:
var item2 = xDoc.XPathSelectElements("//level1/item")
.Select(item => new {
ID = item.Attribute("id").Value,
Name = item.Attribute("name").Value
})
.ToList();
但这完全取决于你的风格 谢谢你,L.B。!但是,我如何查询以获取level1中的所有元素呢?感谢L.B提供了额外的Linq到Xml解决方案。我想我更喜欢Linq到Xml!谢谢你,L.B。!但是,我如何查询以获取level1中的所有元素呢?感谢L.B提供了额外的Linq到Xml解决方案。我想我更喜欢Linq到Xml!
xdoc.Element("level1")
.Descendants("item")
.Where(x => x.Attribute("id").Value == "3").First();