[英]Extracting XML values from two nodes
我想从moduleId属性中提取值,并从Field节点中提取值。 例如,在此第一个节点中,我要从“字段”节点中提取moduleId中的447
和124694
。 我在XDocument中加载了XML。 最终结果将是一个元组,其中第一项是moduleId属性的值,第二项是Field节点的值。 有没有一种方法可以使用一个XLinq语句来做到这一点?
作为奖励...我只想对guid =“ 07a188d3-3f8c-4832-8118-f3353cdd1b73”的节点执行此操作。 这部分我可能可以弄清楚是否有人可以告诉我如何从两个节点中提取信息,但是最好的办法是在其中添加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>
我已经使用此方法提取了Field值...
IEnumerable<string> c = from p in sourceDocument.Descendants("Field")
where p.Attribute("guid").Value == "07a188d3-3f8c-4832-8118-f3353cdd1b73"
select p.Value;
但是我不知道如何从“记录”节点和“字段”节点中获取信息。
试试看:
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();
这是使用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.