我有一个以下格式的xml,当我传递ParentEntityId时需要获取所有SubEntity的id和名称。这需要在silverlight中完成。
<Treeview>
<ParentEntity ParentEntityId="1" ParentEntityName="P1">
<Facility FacilityId="F1" FacilityName="F1">
<Category CategoryId="C1" CategoryName="C1"/>
<Category CategoryId="C2" CategoryName="C2" >
<Activity ActivityId="A1" ActivityName="A1" />
</Category>
</Facility>
<Facility FacilityId="F2" FacilityName="F2">
<Category CategoryId="C1" CategoryName="C1">
<Activity ActivityId="A2" ActivityName="A2" />
<Activity ActivityId="A3" ActivityName="A3" />
</Category>
</Facility>
<SubEntity SubEntityId="S1" SubEntityName="S1">
<SubEntity SubEntityId="S2" SubEntityName="S2"/>
</SubEntity>
<SubEntity SubEntityId="S3" SubEntityName="S3">
<SubEntity SubEntityId="S4" SubEntityName="S4">
<Facility FacilityId="F3" FacilityName="F3">
<Category CategoryId="C1" CategoryName="C1 >
<Activity ActivityId="A1" ActivityName="A1" />
</Category>
</Facility>
</SubEntity>
<SubEntity SubEntityId="S5" SubEntityName="S5">
<Facility FacilityId="F5" FacilityName="F5">
<Category CategoryId="C1" CategoryName="C1" />
<Category CategoryId="C2" CategoryName="C2"/>
</Facility>
</SubEntity>
<SubEntity SubEntityId="S6" SubEntityName="S6" />
</SubEntity>
</ParentEntity>
<ParentEntity ParentEntityId="2" ParentEntityName="P2">
<Facility FacilityId="F1" FacilityName="F1">
<Category CategoryId="C1" CategoryName="C1"/>
</Facility>
<SubEntity SubEntityId="S7" SubEntityName="S7" />
</ParentEntity>
</Treeview>
假设我传递了parentEntityId = 1,我需要输出S1,S2,S3,S4,S5,S6。
提前致谢, Sunitha
答案 0 :(得分:0)
使用LINQ to XML
foreach(XElement subEntity in doc.Root.Elements("ParentEntity")
.First(elem => elem.Attribute("ParentEntityID").Value == "1")
.Descendents("SubEntity") )
{
// Do stuff with each SubEntity e.g.:-
string name = subEntity.Attribute("SubEntityName");
}
如果您使用Silverlight 4,则另一种方法是使用XPath。您需要将System.Xml.XPath.dll添加到您的引用。在这种情况下,上述循环变为: -
foreach(XElement subEntity in doc.Root
.XPathSelectElements("ParentEntity[ParentEntityId='1']//SubEntity" )
{
// Do stuff with each SubEntity e.g.:-
string name = subEntity.Attribute("SubEntityName");
}
顺便说一下,你的真实XML前缀中没有你所放置元素名称的所有属性名称吗?例如,为什么“SubEntityName”而不仅仅是“Name”?