![](/img/trans.png)
[英]how to get specific nested values inside of XML using Linq to XML C# in .Net 5.0
[英]To get first set of values in XML using c# Linq
在下面的XML中,我需要获取FirstNameList的Name属性值,我尝试使用下面的代码,但是我可以获取所有name属性值。我的预期输出是
预期产量:
Sample
NEw Test Application
A1 : 565
A2 : 354
A3 : 2523
A4 : 6756
A5 : 7433
XML
<?xml version="1.0" encoding="utf-8" ?>
<Forum ID="1234">
<ForumName>Sample</ForumName>
<Description>NEw Test Application</Description>
<NameList>
<Name name="A1" value="565"></Name>
<Name name="A2" value="354"></Name>
<Name name="A3" value="2523"></Name>
<Name name="A4" value="6756"></Name>
<Name name="A5" value="7433"></Name>
</NameList>
<Threads>
<Thread>
<Id>123</Id>
<StepName>543</StepName>
<NameList>
<Name name="A1" value="54|45"></Name>
<Name name="A2" value="342|567"></Name>
<Name name="B1" value="rtsd"></Name>
<Name name="B3" value="432"></Name>
<Name name="A4" value="9087"></Name>
</NameList>
</Thread>
<Thread>
<Id>125</Id>
<StepName>541</StepName>
<NameList>
<Name name="A1" value="51|91"></Name>
<Name name="A2" value="321|578"></Name>
<Name name="B1" value="dgrw"></Name>
<Name name="B3" value="415"></Name>
<Name name="A4" value="876"></Name>
</NameList>
</Thread>
</Threads>
</Forum>
C#代码:
static void Main(string[] args)
{
string path = Directory.GetCurrentDirectory().Replace("\\bin\\Debug","");
path = path + "//XML//XMLFile1.xml";
XDocument xdoc = XDocument.Load(path);
IEnumerable<XElement> elem = from a in xdoc.Descendants("Forum")
select a;
foreach (var item in elem)
{
Console.WriteLine(item.Element("ForumName").Value);
Console.WriteLine(item.Element("Description").Value + "\n");
var firstNameList = from val in item.Descendants("Name")
select new { AttributeName = val.Attribute("name").Value, AttributeVal = val.Attribute("value").Value };
foreach (var NamelistItem in firstNameList)
{
Console.WriteLine(NamelistItem.AttributeName + " : " + NamelistItem.AttributeVal);
}
}
Console.ReadLine();
}
如果只想在第一个NameList
节点中进行迭代,则可以使用IEnumerable<T>.First()
方法:
string path = Directory.GetCurrentDirectory().Replace("\\bin\\Debug","");
path = path + "//XML//XMLFile1.xml";
XDocument xdoc = XDocument.Load(path);
var firstNameList= xdoc.Descendants("Forum").First()
.Descendants("NameList").First()
.Descendants("Name")
.Select(val => new { AttributeName = val.Attribute("name").Value, AttributeVal = val.Attribute("value").Value })
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.