【发布时间】:2021-09-14 05:21:28
【问题描述】:
如何选择标签“lat”并根据我想要的“eventid”获取值“123”?例如,我想选择<lle:eventid>ID1</lle:eventid>中的<lle:lat>123</lle:lat>而不使用XPath,只使用LINQ to XML
预期输出:
123
下面是xml文件:
<soapenv:Letter xmlns:soapenv="http://www.w3.org/2001/12/soap-envelope" soapenv:encodingStyle="http://www.w3.org/2001/12/soap-encoding" >
<soapenv:Body xmlns:lle="http://www.aab.org/lifelogevents" >
<lle:Event>
<lle:eventid>ID1</lle:eventid>
<lle:tweet>
<lle:text>This is some tweet in my day</lle:text>
<lle:location>
<lle:lat>123</lle:lat>
<lle:long>456</lle:long>
</lle:location>
</lle:tweet>
</lle:Event>
<lle:Event>
<lle:eventid>ID2</lle:eventid>
<lle:instagram-post-update>
<lle:text>This is some status update in my day</lle:text>
<lle:location>
<lle:lat>789</lle:lat>
<lle:long>987</lle:long>
</lle:location>
</lle:instagram-post-update>
</lle:Event>
</soapenv:Body>
</soapenv:Letter>
到目前为止,这是我的 C# 代码:
XDocument xmldoc = XDocument.Load(@"C:\Users\JACK\source\repos\LINQ_Learn\LINQ_Learn\xmlFile.xml");
XNamespace lle = "http://www.aab.org/lifelogevents";
XNamespace soapenv = "http://www.w3.org/2001/12/soap-envelope";
var lati = from data in xmldoc.Descendants(nlle + "Event")
where (string)data.Element(nlle + "eventid") == "ID1"
select data.Element(nlle + "lat").Value;
foreach(var lat in lati)
{
Console.WriteLine(lat);
}
【问题讨论】:
标签: c# linq-to-xml