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? :)

7
  • Checkout this StackOverFlow Posting it should lend you some ideas stackoverflow.com/questions/8194155/c-sharp-parse-xml-file Commented Oct 10, 2012 at 16:56
  • can you show us the xml and what u and from it! Commented Oct 10, 2012 at 16:57
  • Why don't you just use XMLReader? Commented Oct 10, 2012 at 17:06
  • @Ramhound: Sadly I am new to this c# wpf world. I have not worked on it yet Commented Oct 10, 2012 at 17:06
  • 1
    I just posted it to the bottom of my first answer.. it would also help if you could show the format of your XML File because there are many ways to skin a cat if you know what I mean Commented Oct 10, 2012 at 17:15

3 Answers 3

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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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
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.

7 Comments

The OP is a C++ developer Rakesh so perhaps you could show a code sample to help him out.. hopefully he understands Linq
@StonedJesus: No worries mate... Is above example helpful for you? you can also use LINQPad to intuitively create a query . linqpad.net
@RakeshGunijan: Thanks buddy :) but I have not worked on LINQ at all.
Can you share a pseudo xml structure (Fill dummy data). I can then provide you the query for it.
@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 :)
|
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;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.