简体   繁体   中英

Get all XML Nodes with Child elements and their values in C#

I am using this XML structre

<root>  
  <StandardValues>    
      <ButtonYES>Ja</ButtonYES>
      <ButtonNO>Nei</ButtonNO>
  <tooltips>
    <tooltipOK>OK</tooltipOK>
    <tooltipCancel>Cancel</tooltipCancel>
  </tooltips>
  </StandardValues>
  <Page1>
    <Key_Head alias="custom value">2011 Applications</Key_Head>
    <Key_Title alias="custom values scsc">Title from 2011</Key_Title>
    <Key_Param1>Parameter value</Key_Param1>
  </Page1>
  <Page2>
      <Page_Head>2011 Applications</Page_Head>
      <page_Title>Title from 2011</page_Title>
      <CustomParam1>Parameter value</CustomParam1>
  </Page2>
</root> 

How can i find child nodes values alone as a List .

For example here in this XML Page1 have 3 child nodes i just want those 3 names and its values No need to include Nodes like "root" "StandardValues" "tooltips" "Page2" "Page1" etc in the result list . I just want the XML Elements in the very base level with some values only

I tried this but no success

var elements_list = doc.Root
                        .Elements().Where(p=>p.HasElements==false)
                        .Select(d => new
                        {
                            NodeName = (string)d.Name.LocalName,
                            Value = d.Value, // equal to id you are searching for
                            AttributeValue = (d.Attribute("alias") != null) ? 
                                                d.Attribute("alias").Value : ""  
                        }).ToList();

foreach (var s in elements_list)
{
    string ss = string.Format("{0} -  {1} && {2}", s.NodeName, s.Value, s.AttributeValue);
}

Elements method returns element's direct children only and not sub-children.

Use Descendants instead:

 doc.Root.Descendants().Where(p=>!p.HasElements).Select(....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM