0

I am a c++ developer and I started working on a C# WPF project. I have a method which should read the xml file. In my c++ application I could do it very efficiently but in WPF I am not sure how to approach the problem. Let me show you my code:

// When Browse Button is clicked this method is called
private void ExecuteScriptFileDialog()
    {
        var dialog = new OpenFileDialog { InitialDirectory = _defaultPath };
        dialog.DefaultExt = ".xml";
        dialog.Filter = "XML Files (*.xml)|*.xml";
        dialog.ShowDialog();
        ScriptPath = dialog.FileName; //ScriptPath contains the Path of the Xml File
        if (File.Exists(ScriptPath))
        {
            LoadAardvarkScript(ScriptPath);
        }
    }

    public void LoadAardvarkScript(string ScriptPath)
    {
        // I should read the xml file
    }

I had achieved in C++ as follows:

File file = m_selectScript->getCurrentFile(); //m_selectScript is combobox name
if(file.exists())
{
   LoadAardvarkScript(file);
}

void LoadAardvarkScript(File file)
{   

XmlDocument xmlDoc(file);

//Get the main xml element
XmlElement *mainElement = xmlDoc.getDocumentElement();
XmlElement *childElement = NULL;
XmlElement *e = NULL;
int index = 0;
if(!mainElement )
{
    //Not a valid XML file.
    return ;
}

//Reading configurations...
if(mainElement->hasTagName("aardvark"))
{
    forEachXmlChildElement (*mainElement, childElement)
    {
        //Read Board Name
        if (childElement->hasTagName ("i2c_write"))
        {
            // Some code
        }
    }
}

How can I get the tagname of both mainElement and childelem as done in my c++ code? :)

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
StonedJesus
  • 397
  • 1
  • 5
  • 26

3 Answers3

1

not knowing the layout of your xml file here is an example that you can use if you know how to use Linq

class Program
{
    static void Main(string[] args)
    {
        XElement main = XElement.Load(@"users.xml");

        var results = main.Descendants("User")
            .Descendants("Name")
            .Where(e => e.Value == "John Doe")
            .Select(e => e.Parent)
            .Descendants("test")
            .Select(e => new { date = e.Descendants("Date").FirstOrDefault().Value, points = e.Descendants("points").FirstOrDefault().Value });

        foreach (var result in results)
            Console.WriteLine("{0}, {1}", result.date, result.points);
        Console.ReadLine();
    }
}

you could also use XPATH as well to parse xml file.. but would really need to see the xml file layout

if you want to do it using xmlreader

using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml;

namespace XmlReading
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of the XmlTextReader and call Read method to read the file            
            XmlTextReader textReader = new XmlTextReader("C:\\myxml.xml");
            textReader.Read();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(textReader);

            XmlNodeList BCode = xmlDoc.GetElementsByTagName("Brandcode");
            XmlNodeList BName = xmlDoc.GetElementsByTagName("Brandname");
            for (int i = 0; i < BCode.Count; i++)
            {
                if (BCode[i].InnerText == "001")
                    Console.WriteLine(BName[i].InnerText);                
            }

            Console.ReadLine();
        }
    }
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • Wouldn't it be easier to use XMLReader in a case like this? Why complicate the problem by using LINQ unless its a really complicate XML document. – Security Hound Oct 10 '12 at 17:09
  • @DJKRAZE: First of all thanks a lot for helping :) Thats the problem mate. XML file is in my office desktop and I dont know the structure. Now i don have access to it. I can provide you the file tomorrow same time. I hope you are gonna be online on Stackoverflow – StonedJesus Oct 10 '12 at 17:19
0

Use LINQ queries to extract data from xml (XDocument)

Refer this link for further insights on XLinq.

Sample XML :

 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<People>
<Person id="1">
<Name>Joe</Name>
<Age>35</Age>
<Job>Manager</Job>
</Person>

<Person id="2">
<Name>Jason</Name>
<Age>18</Age>
<Job>Software Engineer</Job>
</Person>

</People>

Sample Linq query:

var names = (from person in Xdocument.Load("People.xml").Descendants("Person")
        where int.Parse(person.Element("Age").Value) < 30
        select person.Element("Name").Value).ToList();

Names will be list of string. This query will return Jason as he is 18 yrs old.

RockWorld
  • 1,278
  • 2
  • 11
  • 24
  • 1
    The OP is a C++ developer Rakesh so perhaps you could show a code sample to help him out.. hopefully he understands Linq – MethodMan Oct 10 '12 at 16:57
  • @StonedJesus: No worries mate... Is above example helpful for you? you can also use LINQPad to intuitively create a query . http://www.linqpad.net/ – RockWorld Oct 10 '12 at 17:06
  • @RakeshGunijan: Thanks buddy :) but I have not worked on LINQ at all. – StonedJesus Oct 10 '12 at 17:08
  • Can you share a pseudo xml structure (Fill dummy data). I can then provide you the query for it. – RockWorld Oct 10 '12 at 17:13
  • @RakeshGunijan: Thats the problem mate. XML file is in my office desktop and I dont know the structure. Now i don have access to it. I can provide you the file tomorrow same time. I hope you are gonna be online on Stackoverflow :) – StonedJesus Oct 10 '12 at 17:16
  • No worries, add new comment below, I will get notification. – RockWorld Oct 10 '12 at 17:20
  • @RakeshGunijan: Thanks a lot. In next 8 hours ill access the file. Will post the xml structure and drop a comment immediately :) – StonedJesus Oct 10 '12 at 17:22
0

Using Linq2Xml,

var xDoc = XDocument.Load("myfile.xml");

var result = xDoc.Descendants("i2c_write")
                .Select(x => new
                {
                    Addr = x.Attribute("addr").Value,
                    Count = x.Attribute("count").Value,
                    Radix = x.Attribute("radix").Value,
                    Value = x.Value,
                    Sleep = ((XElement)x.NextNode).Attribute("ms").Value 
                })
                .ToList();

var khz = xDoc.Root.Element("i2c_bitrate").Attribute("khz").Value;
L.B
  • 114,136
  • 19
  • 178
  • 224