Hey

What is the easiest way to read and write XML file to my C# program? Im looking for

Localiziation
Configuration

I imagine that the only difference is that I have to load the localization as soon as I load the program....

Thanks! :)

Recommended Answers

All 14 Replies

The System.Xml.Linq namespace is the easiest to use (in my opinion).
What changes are you expecting to make in different locales/countries?

try this to get xml fields to dataset then to gridview:

add namespace : using System.Xml.Linq;

        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("Events.xml"));
        GridView1.DataSource = ds.Tables[0].DefaultView;
        GridView1.DataBind();

I don't know about the localization or configuration bit but i did the code below to import data from an Xml file. I used an OpenFileDialogBox (fileOK method belongs to OpenFileDialogBox) and created a class called ObjectTypeState containing get/ set properties to store the imported data which was then displayed in a propertyGrid.

using System.Xml;

ObjectTypeState objtyp = new ObjectTypeState();
ObjectTypeState objtype1 = new ObjectTypeState();

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            try
            {
                string path = openFileDialog1.FileName.ToString();
        }
            catch (Exception ex)
            {
                throw (new Exception("Could not import state " + ex));
            }
        }

    public ObjectTypeState importState(string path)
        {
            try
            {
                //Initialises instance of XmlDocument class called config
                XmlDocument config = new XmlDocument();

                //Loads existing Xml document, located at directory this is stored in path and stores it into config
                config.Load(path);

                //Creates instance of all node within loaded Xml docuemnt and retrieves element by tag name
                XmlNodeList ObjectTypeID = config.GetElementsByTagName("ObjectID");

                //Loops through foreach for each element specified by GetElementByTagName("")
                foreach (XmlNode n in ObjectTypeID)
                {
                    //Converts XmlNode to XmlElement
                    XmlElement _ObjectTypeID = (XmlElement)n;

                    //Converts and stroes value of specified attribute in property of ObjectTypeState class
                    objtyp.ObjectTypeID = Convert.ToInt32(_ObjectTypeID.GetAttribute("ID"));
                }

                XmlNodeList StateType = config.GetElementsByTagName("StateType");

                foreach (XmlNode n in StateType)
                {
                    XmlElement _statetype = (XmlElement)n;
                    objtyp.StateType = Convert.ToInt32(_statetype.GetAttribute("ID"));
                }   

            }
            catch (Exception e)
            {
                MessageBox.Show("Could not import file contents. Exception: " + e);
            }
            //Returns instance of ObjectTypeState class
            return objtyp;
        }

Hope this helps. (the code that goes on two lines are comments.

The System.Xml.Linq namespace is the easiest to use (in my opinion).
What changes are you expecting to make in different locales/countries?

Languages.....I may not have understood you or you might not have understood me because I think thats why you localization in implemented right?

Ive heard about LINQ but I see it more like "SQL" type thing, non related to localization.

try this to get xml fields to dataset then to gridview:

add namespace : using System.Xml.Linq;
1. DataSet ds = new DataSet();2. ds.ReadXml(Server.MapPath("Events.xml"));3. >GridView1.DataSource = ds.Tables[0].DefaultView;4. GridView1.DataBind();

Well I dont have any intrest in showing the data (at least not yet) but thanks for that :) Like I said I might problably have to use it in the future.

Im going to try to put a example of what I want to do (note that all I put above is invented code)

Lets say I have a XML file like this:

<config>
    <languages>
    <english>
        <id="textboxlabel" value="Yes" />
    </english>   

    <spanish>
        <id="textboxlabel" value="Si" /> 

    </spanish>
    </languages>
</config>

(I do not even know if that is valid XML. Im just stating it as a example of what I want to do.)

This would be C# code

private void Form1_load()
{
    loadvalues(english,textboxlabel.text,"Yes",lang.xml);
}

private void loadvalues(String language,String /*or object*/ nameofobject,String default,String languagefile)
{
    //ALL THIS IS PSEUDOCODE
    xml x=new xml();
    x.loadfile(languagefile.xml);
    String text=x.getvaluefor(nameofobject,language);
    if ((text=="") || (text==NULL))
    {
        x.setvaluefor(nameofobject,default)
    }   

    else
    {   
        x.setvaluefor(nameofobject,text);
    }

}

Basically that sums up what I want to do.....I hope it is explained correctly.

Is there maybe a alternative for loading/saving configurations and languages? I mean the first that comes to mind is .ini files but I choose XML as .ini is so........"antique"

But if it is easier to work with, Ill go with .ini

Nothing huh.........Ill try with LINQ to XML but that does not look easy at all....

Have a read through these articles about reading and writing to Xml. They are different ways of doing it but should be useful and i did it the way shown in the stack overflow link (the first one, i suggested it in my earlier reply in this thread).

http://stackoverflow.com/questions/1464557/reading-and-writing-an-existing-xml-file-c-sharp-3-0-net3-5

http://www.c-sharpcorner.com/uploadfile/SamTomato/xmlserializer-class-for-reading-and-writing-xml/

http://forum.codecall.net/topic/58239-c-tutorial-reading-and-writing-xml-files/

Also if you want help bumping with comments like the last few probably won't help. It might be a good idea to do a search on DaniWeb for reading and writing Xml because i have seen a few in the past too.

Hope this helps, let me know if you get stuck (c looks like it is a string containing the contact info).

@riahc3, I assume your on about this:

foreach (c in contact.Nodes()) {
   Console.WriteLine(c);
}

In which case c is the local variable name used inside the foreach representing a node in contact.Node object.

Assuming c stands for contact in this case.

Hope this helps, let me know if you get stuck (c looks like it is a string containing the contact info).

} In which case c is the local variable name used inside the foreach representing a node in contact.Node object.

This completely proves my point: One user thinks c is a string (what I though at first) while the other uses it is a contact.Node object. See how it is confusing?

ChrisHunter, my intention was not to bump and I apoligize if it came out that way. I ment that I will try LINQ to XML, I tried then commented that it isnt easy or well explained...

For now, Im using the registry to store/load data but I dont think its going to be a good idea come localization.

Objects have an overridable ToString() method that will at least show you the type of object (as a string) or, if overridden, will show you the contents.

To get the actual value, Elements, Nodes and Attributes can have a .Value property.

System.Xml.XPath and System.Xml.Linq both have their strengths and weaknesses. I preffer the Linq approach, but maybe you won't.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.