-1

I got an XML file which can have several nodes, child nodes, "child child nodes", ... and I'd like to figure out how to get these data in order to store them into my own SQL Server database.

I've read some tutos on internet and also tried some things. At the current moment, I'm able to open and read the file but not to retrieve data. Here's what I'm doing for instance :

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();

        string filePath = @"C:\Users\Desktop\ConsoleApplication1\XmlPersonTest.xml";

        XmlDocument xmlDoc = new XmlDocument();
        if(File.Exists(filePath))
        {

            xmlDoc.Load(filePath);
            XmlElement elm = xmlDoc.DocumentElement;

            XmlNodeList list = elm.ChildNodes;

            Console.WriteLine("The root element contains {0} nodes",
                             list.Count);
        }
        else
        {

            Console.WriteLine("The file {0} could not be located",
                              filePath);
        }

        Console.Read();
    }
}

And here's a small example of what my XML file looks like :

<person>
    <name>McMannus</name>
    <firstname>Fionn</firstname>
    <age>21</age>
    <nationality>Belge</nationality>
    <car>
        <mark>Audi</mark>
        <model>A1</model>
        <year>2013</year>
        <hp>70</hp>
    </car>
    <car>
        <mark>VW</mark>
        <model>Golf 7</model>
        <year>2014</year>
        <hp>99</hp>
    </car>
    <car>
        <mark>BMW</mark>
        <model>Série 1</model>
        <year>2013</year>
        <hp>80</hp>
    </car>
</person>

Any advice or tuto to do that guys?

1
  • Every XmlNode object contains a collection of child XmlNode objects. This is how you can retrieve the nodes and their contents.
    – Roy Dictus
    Aug 20, 2014 at 14:24

2 Answers 2

0

I have made a little method for navigating through xml nodes, using XElement (Linq.Xml):

    public string Get(XElement root, string path)
    {
        if (root== null)
            return null;
        string[] p = path.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
        XElement at = root;
        foreach (string n in p)
        {
            at = at.Element(n);
            if (at == null)
                return null;
        }
        return at.Value;
    }

Using this, you can get the value of an XElement node via Get(root, "rootNode/nodeA/nodeAChild/etc")

2
  • No, I did not know that. I do now. Thanks.
    – pixartist
    Aug 20, 2014 at 14:39
  • With important differences! XPath supports a lot more than just element names to query a document. It also requires you to take namespaces into account (if any), though that is in most cases a good thing.
    – The Dag
    Aug 20, 2014 at 14:59
0

Well, having gone through something similar the other day. You should try the following, initially build a model:

  1. Open your XML Document.
  2. Copy your entire XML Document.
  3. Open Visual Studio.
  4. Click in an area out of your initial class (1b diagram)
  5. Go to Edit in Visual Studio
  6. Paste Special - Paste as XML Classes

1b:

 namespace APICore 
    {
         public class APIParser()
         {
              // Parse logic would go here.
         }

         // You would click here.
    }

When you do that you'll end up with a valid XML Model, which can be accessed through your parser, how you choose to access the XML Web or Local will be up to you. For simplicity I'm going to choose a file:

public class APIParser(string file)
{
     // Person should be Xml Root Element Class.
     XmlSerializer serialize = new XmlSerializer(typeof(Person)); 
     using(FileStream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
          using(XmlReader reader XmlReader.Create(stream))
          {
              Person model = serialize.Deserialize(reader) as Person;
          }
}

So now you've successfully got the data to iterate through, so you can work with your data. Here is an example of how you would:

// Iterates through each Person
foreach(var people in model.Person)
{
     var information = people.Cars.SelectMany(obj => new { obj.Mark, obj.model, obj.year, obj.hp }).ToList();
}

You would do something like that, then write to the database. This won't fit your example perfectly but should point you in a strong direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.