gpt4 book ai didi

c# - 如何读取后代的成员/子节点?

转载 作者:太空宇宙 更新时间:2023-11-03 20:10:27 24 4
gpt4 key购买 nike

我是 XML 新手。如何读取后代的成员/子节点?

<ho> 
<pro NAME="J1">
<type>C1</type>
<ID>2</ID>
<sta ID="A">Junk1</sta>
<sta ID="B">Junk2</sta>
</pro>
<pro NAME="J2">
<type>C2</type>
<ID>3</ID>
<sta ID="A">Junk3</sta>
<sta ID="B">Junk4</sta>
</pro>
</ho>
XDocument doc = XDocument.Load(file);
foreach (XElement element in doc.Descendants("pro"))
{
string pro_attribute = element.Attribute("NAME").Value;
//I can get pro_attribute J2
if ( pro_attribute =="J2")
{
//how to get getJunk 3 and 4 without having to
//read/loop through Junk1 and 2
foreach (XElement element1 in doc.Descendants("sta"))
{
//I could do this, but it will start with Junk 1.
//I want to start with Junk3 instead
}
}
}

最佳答案

使用一点 Linq

var result = doc.Descendants("pro")
.Select(p => new
{
Name = p.Attribute("NAME").Value,
Type = (string)p.Element("type"),
ID = (string)p.Element("ID"),
Stas = p.Descendants("sta")
.Select(sta => new
{
ID = sta.Attribute("ID").Value,
Value = (string)sta
}).ToList()
})
.ToList();

您也可以使用 XPath:

var result = doc.XPathSelectElements("//pro[@NAME='J2']")
.......
.......

关于c# - 如何读取后代的成员/子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20429507/

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