LinQ 到 XML;使用父节点值查询后代

发布于 2024-10-02 03:22:19 字数 580 浏览 1 评论 0原文

您好,我有以下 XML 结构:

<Root>
 <Persons>
  <PersonList Category="Employee">
   <Person Name="John" Id="5" />
   <Person Name="Mary" Id="10" />
  </PersonList>
 </Persons>
</Root>

我希望使用 LinqtoXML,为了获取可用人员的列表,我可以简单地编写此查询:

var persons = from p in myDoc.Descendants("Person")
select p;

现在,我必须做什么才能获取所有人员 where< /strong> PersonList 元素中的类别 = 为特定值?我无法使用 Parent,因为我需要指定 PersonList 元素,因为 XML 的结构可能与此不同,但元素名称不同。 是否可以?

Hi I have the following XML structure:

<Root>
 <Persons>
  <PersonList Category="Employee">
   <Person Name="John" Id="5" />
   <Person Name="Mary" Id="10" />
  </PersonList>
 </Persons>
</Root>

I am looking to use LinqtoXML and in order to get a list of available Person I can simply write this query:

var persons = from p in myDoc.Descendants("Person")
select p;

Now, what I have to do in order to get all the Person where the Category in PersonList Element is = to a specific value? I can't use Parent because I need to specify the PersonList element as the structure of the XML may be different than this one but not the element name.
Is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉城メ夜风 2024-10-09 03:22:19

听起来您正在寻找

var people = myDoc.Descendants("PersonList")
                  .Where(p => p.Attribute("Category").Value == something)
                  .Descendants("Person");

如果您想获取特定 元素的类别,您可以编写

var category = elem.AncestorsAndSelf("PersonList")
                   .First().Attribute("Category").Value;

It sounds like you're looking for

var people = myDoc.Descendants("PersonList")
                  .Where(p => p.Attribute("Category").Value == something)
                  .Descendants("Person");

If you want to get the category of a specific <Person> element, you can write

var category = elem.AncestorsAndSelf("PersonList")
                   .First().Attribute("Category").Value;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文