Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 714405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T05:04:16+00:00 2026-05-14T05:04:16+00:00

I am just learning about LINQ to XML in all its glory and frailty,

  • 0

I am just learning about LINQ to XML in all its glory and frailty, trying to hack it to do what I want to do:

Given an XML file like this –

<list>
<!-- random data, keys, values, etc.-->

  <key>FIRST_WANTED_KEY</key>
  <value>FIRST_WANTED_VALUE</value>
  
  <key>SECOND_WANTED_KEY</key>
  <value>SECOND_WANTED_VALUE</value> <!-- wanted because it's first -->

  <key>SECOND_WANTED_KEY</key>
  <value>UNWANTED_VALUE</value>  <!-- not wanted because it's second -->

  <!-- nonexistent <key>THIRD_WANTED_KEY</key> -->
  <!-- nonexistent <value>THIRD_WANTED_VALUE</value> -->

<!-- more stuff-->
</list>

I want to extract the values of a set of known "wanted keys" in a robust fashion, i.e. if SECOND_WANTED_KEY appears twice, I only want SECOND_WANTED_VALUE, not UNWANTED_VALUE. Additionally, THIRD_WANTED_KEY may or may not appear, so the query should be able to handle that as well. I can assume that FIRST_WANTED_KEY will appear before other keys, but can’t assume anything about the order of the other keys – if a key appears twice, its values aren’t important, I only want the first one. An anonymous data type consisting of strings is fine.

My attempt has centered around something along these lines:

var z = from y in x.Descendants()
        where y.Value == "FIRST_WANTED_KEY"
        select new
        {
          first_wanted_value = ((XElement)y.NextNode).Value,
         //...
        }

My question is what should that ... be? I’ve tried, for instance, (ugly, I know)

second_wanted_value = ((XElement)y.ElementsAfterSelf()
                      .Where(w => w.Value=="SECOND_WANTED_KEY")
                      .FirstOrDefault().NextNode).Value

which should hopefully allow the key to be anywhere, or non-existent, but that hasn’t worked out, since .NextNode on a null XElement doesn’t seem to work.

I’ve also tried to add in a

.Select(t => { 
    if (t==null) 
        return new XElement("SECOND_WANTED_KEY",""); 
    else return t;
})

clause in after the where, but that hasn’t worked either.

I’m open to suggestions, (constructive) criticism, links, references, or suggestions of phrases to search for, etc. I’ve done a fair share of research already.

Edit

Let me add a layer of complexity to this – I should have included this in the first place. Let’s say the XML document looks like this:

<lists>
    <list>
      <!-- as above -->
    </list>
    <list>
      <!-- as above -->
    </list>
</lists>

and I want to extract multiple sets of these key-value pairs. Question/Caution: if SECOND_WANTED_KEY doesn’t appear in the first <list> element but appears in the second, I don’t want to accidentally pick up the second list element’s SECOND_WANTED_KEY.

Edit #2

As another idea, I’ve tried creating a HashSet of the keys that I’m looking for and doing this:

HashSet<string> wantedKeys = new HashSet<string>();
wantedKeys.Add("FIRST_WANTED_KEY");
//...add more keys here
var kvp = from a in x.Descendants().Where(a => wantedKeys.Contains(a.Value))
          select new KeyValuePair<string,string>(a.value,
             ((XElement)a.NextNode).Value);

This gets me all of the key-value pairs, but I’m not sure if it guarantees that I’ll properly "associate" the pairs to their parent `’ element. Any thoughts or comparisons between these two approaches would be helpful.

Status Update 4/9/10

As of right now I’m still mostly thinking the hash set approach is the most preferred. It seems like most of the XML processing done by .NET is done in document order – so far all of my test cases have been working out.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T05:04:16+00:00Added an answer on May 14, 2026 at 5:04 am

    This gets the value of the first <value> element after the first <key> element containing "SECOND_WANTED_KEY":

    XDocument doc;
    
    string result = (string)doc.Root
                               .Elements("key")
                               .First(node => (string)node == "SECOND_WANTED_KEY")
                               .ElementsAfterSelf("value")
                               .First();
    

    Add null checks as desired.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Learning about LINQ Hi everyone, I just want to understand what exactly
I want to understand the actual theory behind types rather than just learning about
I have spent quite a few hours reading and learning about LINQ to XML , but
I am just starting learning about Linq. I wrote some examples but there is
I am just learning about databases and I want to be able to store
I'm just learning about dynamic memory allocation, but there is one thing i'd like
I am just learning about computer vision and C#. It seems like two prominent
I'm just learning about python. I'm fairly new. I have the following code that
I just started learning about CSRF. As per OWASP CSRF Article CSRF is an
I've just started learning about Gimp scripting using Python, and was wondering, how do

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.