gpt4 book ai didi

c# - 如何查询这种结构的xml?

转载 作者:太空宇宙 更新时间:2023-11-03 21:52:56 25 4
gpt4 key购买 nike

 <root>
<level1>
<item id="1" date="" name="" >
<item id="2" date="" name="" >
<item id="3" date="" name="" >
<item id="4" date="" name="" >
<item id="5" date="" name="" >
</level1>
</root>

我有一个类似上面的 xml 结构。

我用过

XmlNodeList xnList = xmlDoc.SelectNodes("/level1");

如果我像上面那样使用xmlnodelist,我怎么才能具体只获取id="3"的元素呢?

或者如果我可以将所有元素存储为 xnlist 中的元素则更有用?

最佳答案

XmlNodeList xnList = xmlDoc.SelectNodes("//level1/item[@id='3']");

如果你想使用 Linq To Xml

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 item2 = xDoc.XPathSelectElements("//level1/item")
.Select(item => new {
ID = item.Attribute("id").Value,
Name = item.Attribute("name").Value
})
.ToList();

关于c# - 如何查询这种结构的xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13634654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com