本文介绍了如何在C#中的特定XML父节点中获取子节点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有xml文件Folders.xml,

Hi,
I hace xml file Folders.xml,

<root>
<Folder name="Planning">
  <subfolder name="Meeting Minuts"/>
  <subfolder name="Weekly Report"/>
  <subfolder name="Monthaly Report"/>
  <subfolder name="Design Image"/>
</Folder>
<Folder name="Engineering">
  <subfolder name="Engineering1"/>
  <subfolder name="Engineering2"/>
  <subfolder name="Engineering3"/>
  <subfolder name="Engineering4"/>
</Folder>
<Folder name="Quality">
  <subfolder name="Quality1"/>
  <subfolder name="Quality2"/>
  <subfolder name="Quality3"/>
  <subfolder name="Quality4"/>
</Folder>
</root>



刨光,工程和质量是组合框元素。当用户选择组合框作为Planing时,我需要显示规划中的所有子文件夹,如果他将选择Quality,那么所有子文件夹都应该显示,



我怎么能得到特定父母的子元素,



我尝试过:



这是获取Parent元素的代码。


Planing, Engineering and quality are the combobox element. When user will select combobox as Planing the i need to dispaly all the subfolder in the planning, if he will select Quality then all the subfolder should display,

How can I get subelement of perticular parent,

What I have tried:

here is the code to get Parent element.

XDocument myxml = XDocument.Load(@"Xml\Folders.xml");
            string str = string.Empty;
            foreach (XElement level1Element in XElement.Load(@"Xml\Folders.xml").Elements("Folder"))
            {
                str=(level1Element.Attribute("name").Value);
                Folders.Add(str);
            }
            cmb1.ItemsSource = Folders;

推荐答案

string folder = "Quality";
var subfolders = myxml.Root.Elements("Folder")
		.Where(x=>x.Attribute("name").Value==folder)
		.SelectMany(x=>x.Elements("subfolder")
                                .Select(y=>y.Attribute("name").Value))
		.ToList();



结果:


Result:

Quality1
Quality2
Quality3
Quality4 


这篇关于如何在C#中的特定XML父节点中获取子节点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 01:50