[英]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.