Solved

reading xml elements based on dynamic element names using VS2008 c# and linq to xml

Posted on 2012-03-29
7
444 Views
Last Modified: 2012-03-29
Let's say that I have an xml file that looks like this:
<ord>
  <line>
    <sku>123456</sku>
  </line>
</ord>

Let's also say that I have no control over the xml file (it's incoming) and the producer of the file could change it at any time to be:
<order>
  <lineinfo>
    <itemnumber>123456</itemnumber>
  </lineinfo>
</order>

In my VS2008 c# program, is it even possible to set up a configuration that says something like "find the item number at <ord><line><sku>" then read the xml file (using linq to xml) "dynamically"?

I guess, another way of putting it would be can I assign string variables, such as El1, El2, El3 and set them equal to "ord", "line", and "sku", respectively, then read for those elements using the variable names instead of the element names?

Thanks in advance for your thoughts on this.
0
Comment
Question by:g_johnson
  • 4
  • 3
7 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37784426
What are you trying to extract? I'm having an interesting time trying to determine what the end goal is. It seems like you want the flexibility of retrieving data from the XML without having to worry (excessively) about the incoming XML structure. But I think I might be missing something with regard to El1, 2, & 3.
0
 
LVL 4

Author Comment

by:g_johnson
ID: 37784441
I think a better way of putting it is I don't want to hard-code the element names.  If the xml file provider should change an element name, I want to be able to change that in a configuration file instead of re-coding the application.

I liken this to parsing a tab-delimited text file.  In order to avoid hard coding, I will put an entry in my config file to say that item number is in the third field.  Then, if the incoming file format changes, and all of a sudden the item number is in the thirteenth field, all I have to do is change my config file.  I don't have to re-code.

Does that make sense?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37784449
Sure. So what exactly would you be storing in El1 and El2? It seems to me that El3 corresponds to the value of "sku" (or "itemnumber", depending). If that's the case, what would you be storing for "ord" (and "order") and "line" (and "lineinfo")?
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 4

Author Comment

by:g_johnson
ID: 37784513
I don't know that I need El1 and El2, but what I want to do is to say

"item number" is actually found in the element "sku" (El3) which is a subelement of "line" (El2) which is a subelement of "ord" (El1).

Then I would want to design my linq to xml statement to use the variables instead of the actual element names.

Again, I don't know if this is possible.  I'm looking for ideas and this is the best I could come up with, even though I'm not sure how it would work.

Meanwhile I'm asking my client if he will accept a hard-coded solution which puts the burden on the provider of the xml file.  :-)  Really, though, I would like to make it dynamic and configurable and avoid hard-coding if at all possible.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37784554
I think XPath would probably suit this scenario. For example, using the XML you posted above (file1 and file2, respectively) and some XPath magic:

using System;
using System.Xml.Linq;
using System.Xml.XPath;

namespace _27654891
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Load("file1.xml");

            foreach (var node in xdoc.XPathSelectElements("//ord/line/sku"))
            {
                Console.WriteLine(node.Value);
            }

            xdoc = XDocument.Load("file2.xml");

            foreach (var node in xdoc.XPathSelectElements("//order/lineinfo/itemnumber"))
            {
                Console.WriteLine(node.Value);
            }

            Console.ReadKey();
        }
    }
}

Open in new window


The XPath breaks down as:

At any level ( // ) look for an "ord" element ( ord ), and it should have a child named "line" ( /line ), and that child should have a child named "sku" ( /sku ). The effect of the XPath selection is that all "sku" element are chosen, provided they have the appropriate parents. The XPath for the file2 is the same in meaning; just substitute the appropriate name in each part of the XPath.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 37784569
P.S.

Since the XPath itself is a string, you can store it in a file or a database, pass it via the command line, or some other method of passing strings to suit your "configurable" requirement.
0
 
LVL 4

Author Closing Comment

by:g_johnson
ID: 37784652
Excellent!  I'd give you more than 500 points if I could!

In a couple of minutes, I'm going to post another question to take this concept a little further.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Code works but it's slow 28 71
C# Comparing String Arrays. 5 41
Cant save 3D 4 21
Sort GridView by ID Descending 1 13
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question