[英]Extracting XML values from two nodes
I want to extract the value in the moduleId attibute and the value from the Field node. 我想从moduleId属性中提取值,并从Field节点中提取值。 For example, in this first node I want to extract the 447
in the moduleId and the 124694
from the Field node. 例如,在此第一个节点中,我要从“字段”节点中提取moduleId中的447
和124694
。 I have the XML loaded in an XDocument. 我在XDocument中加载了XML。 The end result will be a Tuple where the first item is the value from the moduleId attribute and the second item is the value from the Field node. 最终结果将是一个元组,其中第一项是moduleId属性的值,第二项是Field节点的值。 Is there a way I can do this using one XLinq statement? 有没有一种方法可以使用一个XLinq语句来做到这一点?
As a bonus...I only want to do it for nodes where the guid = "07a188d3-3f8c-4832-8118-f3353cdd1b73". 作为奖励...我只想对guid =“ 07a188d3-3f8c-4832-8118-f3353cdd1b73”的节点执行此操作。 This part I can probably figure out if someone can tell me how to extract information from two nodes, but a bonus would be to add the WHERE clause in there for me :) 这部分我可能可以弄清楚是否有人可以告诉我如何从两个节点中提取信息,但是最好的办法是在其中添加WHERE子句:)
<Records>
<Record moduleId="447">
<Field guid="07a188d3-3f8c-4832-8118-f3353cdd1b73">124694</Field>
</Record>
<Record moduleId="447">
<Field guid="07a188d3-3f8c-4832-8118-f3353cdd1b73">124699</Field>
</Record>
<Records>
I have gotten as far as extracting the Field value using this... 我已经使用此方法提取了Field值...
IEnumerable<string> c = from p in sourceDocument.Descendants("Field")
where p.Attribute("guid").Value == "07a188d3-3f8c-4832-8118-f3353cdd1b73"
select p.Value;
But I have no idea how to get information from both the Record node and the Field node. 但是我不知道如何从“记录”节点和“字段”节点中获取信息。
Give this a try: 试试看:
var doc = XDocument.Parse(xml);
var r = doc.Descendants("Record")
.Where(n => n.Element("Field").Attribute("guid").Value == "07a188d3-3f8c-4832-8118-f3353cdd1b73")
.Select(n => new { ModuleId = n.Attribute("moduleId").Value, Field = n.Element("Field").Value });
var a = r.ToArray();
Here is a solution that uses LINQ Query Syntax: 这是使用LINQ查询语法的解决方案:
XDocument document = XDocument.Parse(xml);
var query =
from el in document.Root.Elements("Record")
where (string)el.Element("Field").Attribute("guid") ==
"07a188d3-3f8c-4832-8118-f3353cdd1b73"
select new
{
ModuleId = (string)el.Attribute("moduleId"),
Field = (string)el.Element("Field")
};
foreach (var item in query)
{
Console.WriteLine
("ModuleId:[{0}]\nField:[{1}]\n--",
item.ModuleId,
item.Field);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.