Solved

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

Posted on 2012-03-29
7
442 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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 4

Author Comment

by:g_johnson
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

763 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now