我需要一些LINQ to XML的帮助。我很想恢复到XPath,但我非常渴望正确学习LINQ to XML。 以下是我的XML的精简版本:
<SData Key="626">
<Event OID="INITIALVISIT">
<FData FID="MODAL_V10">
<IGData IOID="MODALITYTABLE">
<Item OID="I_TABLE_MODAL_DATE_TABLE" Value="2015-06-03" />
<Item OID="I_TABLE_MODAL_TYPE_TABLE" Value="1" />
</IGData>
<IGData IOID="MODALITYTABLE2">
<Item OID="I_TABLE_MODAL_DATE_TABLE2" Value="2015-06-09" />
<Item OID="I_TABLE_MODAL_TYPE_TABLE2" Value="1" />
</IGData>
</FData>
<FData FID="UPLOAD_V40">
<IGData IOID="IG_IMAGE_UNGROUPED">
<Item OID="I_IMAGE_UPLOAD_XNAT" Value="1" />
<Item OID="I_IMAGE_UPLOAD_COMPLETE" Value="1" />
</IGData>
<IGData IOID="IG_IMAGE_UPLOAD">
<Item OID="I_IMAGE_UPLOAD_XNAT" Value="1" />
<Item OID="I_IMAGE_UPLOAD_COMPLETE" Value="1" />
</IGData>
</FData>
</Event>
<Event OID="FOLLOWUPVISIT">
...
...
</Event>
我想要实现的是每个事件都获得AttributeOID =“I_IMAGE_UPLOAD_COMPLETE”的Item的值。这是我到目前为止所做的。
XNamespace occ = "http://www.cdisc.org/ns/odm/v1.3";
XNamespace aoc = "http://www.openclinica.org/ns/odm_ext_v130/v3.1";
var datasubject = data_oc.Descendants(occ + "SData");
var event = datasubject.Elements(occ + "Event").Attributes("OID");
foreach (var items in event)
{
string EventTypes = items.Value.ToString();
foreach (var itemData in EventTypes)
{
var Data = from el in datasubject.Descendants(occ + "Event")
where (string)el.Attribute("OID=") == itemData
select(string)el;
}
}
谢谢。
答案 0 :(得分:0)
var doc=XDocument.Parse(@"your xml");
//Via Linq
var viaLinq=doc.Elements()
.SelectMany(e => e.Elements())
.SelectMany(e => e.Elements())
.SelectMany(e => e.Elements())
.SelectMany(e => e.Elements())
.Where(w => w.Attribute("OID").Value=="I_IMAGE_UPLOAD_XNAT")
.Select(e => e.Attribute("Value").Value);
//Even better use Xpath. It makes all this very simple
var viaXPath=doc.XPathSelectElements("//Item[@OID='I_IMAGE_UPLOAD_XNAT']")
.Select(e => e.Attribute("Value").Value);
答案 1 :(得分:0)
试试这个,不确定它在性能方面是如何运作的。
XDocument po = XDocument.Load("XMLFile1.xml");
// LINQ to XML query
var list1 = po.Descendants("Event")
.Select(x =>
x.Descendants("Item").Where(t =>
(string)t.Attribute("OID") == "I_IMAGE_UPLOAD_COMPLETE").Select(m =>
new { Event = x, AttributeValue = m.Attribute("Value") })
).Where(f => f.FirstOrDefault() != null).ToList();