[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1139
  • Last Modified:

Read/Write XML

Ok I am trying to display information in an XML file. I have a form (view attached image Form 3) which I want the user to be able to view or edit. Basically I want the application to act like this. The admin logs in and opens Form 3. When it opens the default information to display in the textbox based upon what is in the default XML file. Then I want the admin to be able to edit the IP Address, IP Port, and the Configuration Pathway. Can some one please help me with the first part of this which is taking the default information in the XML File and displaying it in the text boxes? After that I tackle the second half.

My XML File code is below in addition to the form code that I have so far.
Untitled.png
0
seahna
Asked:
seahna
  • 14
  • 8
  • 6
  • +1
2 Solutions
 
WesWilsonCommented:
A couple of thoughts on this.

1. Is there a reason you are going with XML instead of a database? You can do either, but I think in the long term you will find a database more manageable. (It sounds from our last discussion as if your boss has mandated XML files, so you don't have a choice.)

2. Please post the XML file you mention, and I'll help you pull out the pieces you are looking for to display. But the basic code will look something like this:


XmlDocument myDoc = new XmlDocument();
  myDoc.Load(@"C:\myFile.xml");
  string xpath = string.Format("To be determined after we see the XML");
  XmlNode myNode= myDoc.SelectSingleNode(xpath);
  string value = myNode.InnerText;

Open in new window

0
 
Fernando SotoCommented:
What version of Visual Studio .Net 2005 or 2008?
0
 
madhevan_pillaiCommented:
Try this


        private void OpenXML()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load("E:\\TestProjectsWeb\\TestWin\\Test.xml"); //add your file path
              string name=  doc.DocumentElement.SelectSingleNode("Name").InnerText ;
              string id = doc.DocumentElement.SelectSingleNode("Id").InnerText;
           
        }
        private void SaveXML(string Name, string Id)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load("E:\\TestProjectsWeb\\TestWin\\Test.xml"); //add your file path
              doc.DocumentElement.SelectSingleNode("Name").InnerText = Name;
              doc.DocumentElement.SelectSingleNode("Id").InnerText=Id;
              doc.Save("E:\\TestProjectsWeb\\TestWin\\Test.xml");  //add your file path
        }


XMl file


<?xml version="1.0" encoding="utf-8"?>
<root>
  <Name>Efgh</Name>
  <Id>5432</Id>
</root>
0
Get quick recovery of individual SharePoint items

Free tool – Veeam Explorer for Microsoft SharePoint, enables fast, easy restores of SharePoint sites, documents, libraries and lists — all with no agents to manage and no additional licenses to buy.

 
seahnaAuthor Commented:
I am using VS2008...Thanks I will look over what is here and ask follow up questions.
0
 
seahnaAuthor Commented:
Ok just notice that my XML file didn't attach sorry about that. Here it is...and I have no clue why my boss wanted to go this way other then him think XML is the greatest thing since sliced bread. It is making my life harder because I knew nothing about XML when I started. Now though I can at least understand some of it of course it doesn't help that I am still a fresh graduate and still learning the tricks of the trade. Thanks for all the help.
<Setup>
  <ACSP>
    <Primary>
      <IPAddress>10.5.105.47</IPAddress>
      <IPPort>61112</IPPort>
      <ConfigurationPath>C:\Projects\AV4.1\DefaultConfig.xml</ConfigurationPath>
    </Primary>
  </ACSP>
</Setup>

Open in new window

0
 
Fernando SotoCommented:
Hi seahna;

Linq to XML makes this simple, see snippet below.

Fernando
using System.Xml;
using System.Xml.Linq;


XDocument doc = XDocument.Load("IPData.xml");

txtIPAddress.Text = doc.Element("Setup").Element("ACSP").Element("Primary").Element("IPAddress").Value;
txtIPPort.Text = doc.Element("Setup").Element("ACSP").Element("Primary").Element("IPPort").Value;
txtConfigFilePath.Text = doc.Element("Setup").Element("ACSP").Element("Primary").Element("ConfigurationPath").Value;

Open in new window

0
 
Fernando SotoCommented:
The location of the file must be a full path with file name unless the file is in the same directory as the executable then just the file name.

XDocument doc = XDocument.Load("IPData.xml");
0
 
madhevan_pillaiCommented:
private void OpenXML()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load("E:\\TestProjectsWeb\\TestWin\\Test.xml"); //add your file path
            string ip = doc.DocumentElement.SelectSingleNode("ACSP/Primary/IPAddress").InnerText;
            string port = doc.DocumentElement.SelectSingleNode("ACSP/Primary/IPPort").InnerText;
            string path = doc.DocumentElement.SelectSingleNode("ACSP/Primary/ConfigurationPath").InnerText;
        }
        private void SaveXML(string ip, string port,string path)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load("E:\\TestProjectsWeb\\TestWin\\Test.xml"); //add your file path
            doc.DocumentElement.SelectSingleNode("ACSP/Primary/IPAddress").InnerText =ip;
            doc.DocumentElement.SelectSingleNode("ACSP/Primary/IPPort").InnerText=port;
             doc.DocumentElement.SelectSingleNode("ACSP/Primary/ConfigurationPath").InnerText=path;
   
              doc.Save("E:\\TestProjectsWeb\\TestWin\\Test.xml");  //add your file path
        }
0
 
Fernando SotoCommented:
Hi seahna;

Here is a less verbose version of my earlier post using the new technology Linq to XML with the save option as well.

Fernando
using System.Xml;
using System.Xml.Linq;


// The location of the XML file.
private string filePath = "C:\\MyPath\\IPData.xml";

private void OpenXMLConfig_Click(object sender, EventArgs e)
{
    XElement ele = XElement.Load(filePath);

    // Fill the text boxes with the values from the XML file
    txtIPAddress.Text = ele.Descendants("IPAddress").FirstOrDefault().Value;
    txtIPPort.Text = ele.Descendants("IPPort").FirstOrDefault().Value;
    txtConfigFilePath.Text = ele.Descendants("ConfigurationPath").FirstOrDefault().Value;

}

private void SaveXMLConfig_Click(object sender, EventArgs e)
{
    XElement ele = XElement.Load(filePath);

    // Save the values to the XML file from the text boxes
    ele.Descendants("IPAddress").FirstOrDefault().Value = txtIPAddress.Text;
    ele.Descendants("IPPort").FirstOrDefault().Value = txtIPPort.Text;
    ele.Descendants("ConfigurationPath").FirstOrDefault().Value = txtConfigFilePath.Text;

    ele.Save("IPData.xml");
}

Open in new window

0
 
seahnaAuthor Commented:
Ok I sorry so long to reply was off for holidays I will look at these and let you know.
0
 
seahnaAuthor Commented:
WesWilson I waited to see what your response was bu tI haven't got one yet so I thought I would try FernandoSoto but I got an error dealing with something else tha tI have to figure out so as soon as I do I'll let you know how it worked...WesWilson I would still like to know your thgoughts if you would like to share them.
0
 
WesWilsonCommented:
Thanks, seahna. There are of course a lot of ways to do this, and I don't know that mine is better than some of the other suggestions. Since you want to focus on reading the XML file into the form, I'll just deal with that right now.

Obviously I'm making up the names of your textboxes, but this should point you in the right direction.


public void PopulateServerForm()
{
  XmlDocument myDoc = new XmlDocument();
  myDoc.Load(@"C:\myFile.xml");
  string ipAddressXpath = string.Format("Setup/ACSP/Primary/IPAddress");
  string ipPortXpath = string.Format("Setup/ACSP/Primary/IPPort");
  string configPathXpath = string.Format("Setup/ACSP/Primary/ConfigurationPath");
  txtIPAddress.Text = ReadValueFromXmlDocumentAtXPath(myDoc, ipAddressXpath);
  txtIPPort.Text = ReadValueFromXmlDocumentAtXPath(myDoc, ipPortXpath);
  txtConfigPath.Text = ReadValueFromXmlDocumentAtXPath(myDoc, configPathXpath);
}

public string ReadValueFromXmlDocumentAtXPath(XmlDocument myDoc, string xpath)
{
  string value = string.Empty;
  XmlNode myNode= myDoc.SelectSingleNode(xpath);
  if(myNode != null && myNode.InnerText != null)
  {
    value = myNode.InnerText;
  }
  return value;
}

Open in new window

0
 
seahnaAuthor Commented:
WesWilson I think you might has answered another problem I was having but here is my question. Is it possible to convert this line from a string to and int?

string ipPortXpath = string.Format("Setup/ACSP/Primary/IPPort");
0
 
WesWilsonCommented:
The value will come back from the XmlDocument as a string, but you can of course call int.Parse(string).

You could put it in a try-catch block or call int.TryParse to handle possible errors. But for simplicity, I'll leave out the error handling.

string ipPortXpath = string.Format("Setup/ACSP/Primary/IPPort");
  string ipPortString = ReadValueFromXmlDocumentAtXPath(myDoc, ipPortXpath);
  int ipPort = int.Parse(ipPortString);

Open in new window

0
 
seahnaAuthor Commented:
Do I need to call something special to use this cause I am getting an error this is:

ReadValueFromXmlDocumentAtXPath

Error      The name 'ReadValueFromXmlDocumentAtXPath' does not exist in the current context


Maybe it will help if you know why I asked if it could be converted...

With this one thing I am trying to do a couple different tasks.

One is to display the information from the XML File to the form in the set text boxes.

Two I am trying to make it so that the user can edit this information and save it back to the XML file stated in the configuration path text box. Meaning if this text filed is edits all new information will be saved in the pathway stated. Otherwise if the user changes it from a:\pathway1\XMLdoc to b:\pathway2\XMLdoc2 all information will now be store in XMLdoc2. ( hope that wasn't confusing)

Thrid I need the application to be able to use this information (IP address & IP port) to connect to a server at this IP address and IP Port.

Here is where I come to my problem the server can only read the IP address as a string which works because it is read from the XML file as a string and so far isn't causing me problems. However the IP port can only be read as and int from the server and it is being pulled in as a string. So I have to convert it to make the application actually connect. (I didn't write the server part of the code or I would switch it and be done with it but I have been told for some reason this con't be done.)

Granted I have the server connection code in a different place but it is the same basic concept read in an XML file and apply settings stored in XML file, but I was trying to kill two birds with one stone by using the same basic code from this discussion. I hope I didn't confuse you and that you understand what it is that I am doing.  
0
 
Fernando SotoCommented:
Hi seahna;

You did not state what kind of error you were getting with my code. Did you remember to put these using statements at the top of your code file?

using System.Xml;
using System.Xml.Linq;

Fernando
0
 
WesWilsonCommented:
Seahna,

The 3 line excerpt in my last comment was just an adaptation of my previous code. ReadValueFromXmlDocumentAtXPath is the function I previously showed.

You can easily go back and forth between a string and an int using int.Parse(string) and the ToString() method of an int.
0
 
seahnaAuthor Commented:
FernandoSoto I didn't get an error with you code I got an error with code somewhere else in my application that I have to correct before I can see if you code works. Sorry I didn't explain that better.

WeWilson Just trying to make use I understand your code. Does the myDoc stand for the the XML file name?
0
 
WesWilsonCommented:
In Line 4 we load the XML file into myDoc, which is an XmlDocument. I made up the name and path "C:\myFile.xml"
0
 
seahnaAuthor Commented:
Ok I had a stupid moment there I should have known that. Ok I have one more error somewhere else in my code to fix and I'll let you know if this works...
0
 
seahnaAuthor Commented:
Ok now that I have all errors fix I ran the application and the form doesn't display any information by the use of FernandoSoto solution. I am going to try your idea now WesWilson
0
 
Fernando SotoCommented:
Can you post your code and the XML file you are using if different then original post.
0
 
seahnaAuthor Commented:
Ok sorry was trying to post the code earlier but my internet went down. So this is what I have now.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Security.Principal;
using System.Xml;
using Stentofon.AlphaCom.AlphaNet.Client;
using Stentofon.AlphaCom.Data.State;

namespace AV4._1_ClientTool.Dialogs1.Configurations
{
    /*
     * The IP Address and Port # are needed when creating an AlphaNetClient object. This AlphaNetClient 
     * construct takes the IP Address and Port# and after assigning them to global variables, those 
     * variables are used when performing a TCP Client Connect() call. It is at this point the connection 
     * is made between the API and the exchange.
     */
    
    public partial class ServerConfigurations : Form
    {
        //private AlphaComState _stateStorage;
        //private AlphaNetClient _alphaNetClient;

        public ServerConfigurations()
        {
            InitializeComponent();
        }

        //read the XML file 
        private static string ConfigFileName = ConfigurationManager.AppSettings["ConfigFileName"];

        #region Text Field Display
        public void PopulateServerForm()
        {
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(ConfigFileName);
            string ipAddressXpath = string.Format("Setup/ACSP/Primary/IPAddress");
            string ipPortXpath = string.Format("Setup/ACSP/Primary/IPPort");
            string configPathXpath = string.Format("Setup/ACSP/Primary/ConfigurationPath");
            IPaddressBox.Text = ReadValueFromXmlDocumentAtXPath(myDoc, ipAddressXpath);
            IPportBox.Text = ReadValueFromXmlDocumentAtXPath(myDoc, ipPortXpath);
            ConfigPathBox.Text = ReadValueFromXmlDocumentAtXPath(myDoc, configPathXpath);
        }

        public string ReadValueFromXmlDocumentAtXPath(XmlDocument myDoc, string xpath)
        {
            string value = string.Empty;
            XmlNode myNode = myDoc.SelectSingleNode(xpath);
            if (myNode != null && myNode.InnerText != null)
            {
                value = myNode.InnerText;
            }
            return value;
        }

       #endregion Text Field Display

        #region Buttons
        private void evOKPS1_Click(object sender, EventArgs e)
        {//upon Ok button pressed stores IP Address and IP Port then closes window

            //Store & Apply IPaddressBox, IPportBox, ConfigPathBox
            XElement ele = XElement.Load(ConfigFileName);

            // Save the values to the XML file from the text boxes 
            ele.Descendants("IPAddress").FirstOrDefault().Value = IPaddressBox.Text;
            ele.Descendants("IPPort").FirstOrDefault().Value = IPportBox.Text;
            ele.Descendants("ConfigurationPath").FirstOrDefault().Value = ConfigPathBox.Text;

            ele.Save("IPData.xml"); 

            this.Hide();
        }

        private void evApplyPS1_Click(object sender, EventArgs e)
        {//instantly stores IP Address and IP Port but does not close window
            //Store & Apply IPaddressBox, IPportBox, ConfigPathBox
            XElement ele = XElement.Load(ConfigFileName);

            // Save the values to the XML file from the text boxes 
            ele.Descendants("IPAddress").FirstOrDefault().Value = IPaddressBox.Text;
            ele.Descendants("IPPort").FirstOrDefault().Value = IPportBox.Text;
            ele.Descendants("ConfigurationPath").FirstOrDefault().Value = ConfigPathBox.Text;

            ele.Save("IPData.xml"); 
        }

        private void evCancelPS1_Click(object sender, EventArgs e)
        {//Closes the window without saving or editing information
            this.Hide();
        }
        #endregion Buttons
    }
}

Open in new window

0
 
Fernando SotoCommented:
Hi seahna;

If the names of the three text boxes are IPaddressBox, IPportBox and ConfigPathBox then I do not see a reason why it is not creating the xml file in the same directory as the executable is in, if in Debug build it should be in a sub-directory of the project bin/debug.

Fernando
0
 
seahnaAuthor Commented:
The application does load without error in Debug but when I open the form that displays this information it doesn't display anything except the form structure.
0
 
Fernando SotoCommented:
Hi seahna;

Well in the code you posted last you have two button event handlers which loads the xml document and then writes the values in the text boxes to the xml elements and then saves the modified elements back to the file. In order to display the data in the text boxes you need to load the data from the xml to the text boxes as shown in the code snippet below.

Fernando
private void OpenXMLConfig_Click(object sender, EventArgs e)
{
    XElement ele = XElement.Load(filePath);

    // Fill the text boxes with the values from the XML file
    txtIPAddress.Text = ele.Descendants("IPAddress").FirstOrDefault().Value;
    txtIPPort.Text = ele.Descendants("IPPort").FirstOrDefault().Value;
    txtConfigFilePath.Text = ele.Descendants("ConfigurationPath").FirstOrDefault().Value;

}

Open in new window

0
 
seahnaAuthor Commented:
I am sorry that is the same code you gave me before that didn't work and I tried it again to make sure and it still doesn't work nothing gets displayed in the text box field. Code attached below just so you can see.
namespace AV4._1_ClientTool.Dialogs1.Configurations
{
    /*
     * The IP Address and Port # are needed when creating an AlphaNetClient object. This AlphaNetClient 
     * construct takes the IP Address and Port# and after assigning them to global variables, those 
     * variables are used when performing a TCP Client Connect() call. It is at this point the connection 
     * is made between the API and the exchange.
     */
    
    public partial class ServerConfigurations : Form
    {
        //private AlphaComState _stateStorage;
        //private AlphaNetClient _alphaNetClient;

        public ServerConfigurations()
        {
            InitializeComponent();
        }

        //read the XML file 
        private static string ConfigFileName = ConfigurationManager.AppSettings["ConfigFileName"];

        #region Text Field Display

        private void OpenXMLConfig_Click(object sender, EventArgs e)
        {
            XElement ele = XElement.Load(ConfigFileName);

            // Fill the text boxes with the values from the XML file 
            IPaddressBox.Text = ele.Descendants("IPAddress").FirstOrDefault().Value;
            IPportBox.Text = ele.Descendants("IPPort").FirstOrDefault().Value;
            ConfigPathBox.Text = ele.Descendants("ConfigurationPath").FirstOrDefault().Value;

        }

        public string ReadValueFromXmlDocumentAtXPath(XmlDocument myDoc, string xpath)
        {
            string value = string.Empty;
            XmlNode myNode = myDoc.SelectSingleNode(xpath);
            if (myNode != null && myNode.InnerText != null)
            {
                value = myNode.InnerText;
            }
            return value;
        }

       #endregion Text Field Display

        #region Buttons
        private void evOKPS1_Click(object sender, EventArgs e)
        {//upon Ok button pressed stores IP Address and IP Port then closes window

            //Store & Apply IPaddressBox, IPportBox, ConfigPathBox
            XElement ele = XElement.Load(ConfigFileName);

            // Save the values to the XML file from the text boxes 
            ele.Descendants("IPAddress").FirstOrDefault().Value = IPaddressBox.Text;
            ele.Descendants("IPPort").FirstOrDefault().Value = IPportBox.Text;
            ele.Descendants("ConfigurationPath").FirstOrDefault().Value = ConfigPathBox.Text;

            ele.Save("IPData.xml"); 

            this.Hide();
        }

        private void evApplyPS1_Click(object sender, EventArgs e)
        {//instantly stores IP Address and IP Port but does not close window
            //Store & Apply IPaddressBox, IPportBox, ConfigPathBox
            XElement ele = XElement.Load(ConfigFileName);

            // Save the values to the XML file from the text boxes 
            ele.Descendants("IPAddress").FirstOrDefault().Value = IPaddressBox.Text;
            ele.Descendants("IPPort").FirstOrDefault().Value = IPportBox.Text;
            ele.Descendants("ConfigurationPath").FirstOrDefault().Value = ConfigPathBox.Text;

            ele.Save("IPData.xml"); 
        }

        private void evCancelPS1_Click(object sender, EventArgs e)
        {//Closes the window without saving or editing information
            this.Close();
        }
        #endregion Buttons
    }
}

Open in new window

0
 
WesWilsonCommented:
I would set a break point at line 27 and step the code. It might be that the event isn't hooked up correctly to ever run this code. Sometimes the simple things are easy to overlook. Breakpoints and tracing can be a lifesaver.
0
 
seahnaAuthor Commented:
Ok got it fixed it displays the text now I forgot to wire the stupid things up. You would think I would learn that lesson by now. thanks a lot guys for all you help on the display part and I tested both of your codes they both work perfect on the display part. Now I need to figure out how to edit the XML document. from the same screen.

FernandoSoto I tried the code you orginally gave me but it doesn't work. However so this disucssion doesn't get too long and complixed I am going to start a new one about that. I attached a final working copy of the code I am using.
namespace AV4._1_ClientTool.Dialogs1.Configurations
{
    /*
     * The IP Address and Port # are needed when creating an AlphaNetClient object. This AlphaNetClient 
     * construct takes the IP Address and Port# and after assigning them to global variables, those 
     * variables are used when performing a TCP Client Connect() call. It is at this point the connection 
     * is made between the API and the exchange.
     */
    
    public partial class ServerConfigurations : Form
    {
        //private AlphaComState _stateStorage;
        //private AlphaNetClient _alphaNetClient;

        public ServerConfigurations()
        {
            InitializeComponent();
        }

        //read the XML file 
        private static string ConfigFileName = ConfigurationManager.AppSettings["ConfigFileName"];

        #region Text Field Display

        public void PopulateServerForm(object sender, EventArgs e)
        {
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(ConfigFileName);
            string ipAddressXpath = string.Format("Setup/ACSP/Primary/IPAddress");
            string ipPortXpath = string.Format("Setup/ACSP/Primary/IPPort");
            string configPathXpath = string.Format("Setup/ACSP/Primary/ConfigurationPath");
            IPaddressBox.Text = ReadValueFromXmlDocumentAtXPath(myDoc, ipAddressXpath);
            IPportBox.Text = ReadValueFromXmlDocumentAtXPath(myDoc, ipPortXpath);
            ConfigPathBox.Text = ReadValueFromXmlDocumentAtXPath(myDoc, configPathXpath);
        }

        public string ReadValueFromXmlDocumentAtXPath(XmlDocument myDoc, string xpath)
        {
            string value = string.Empty;
            XmlNode myNode = myDoc.SelectSingleNode(xpath);
            if (myNode != null && myNode.InnerText != null)
            {
                value = myNode.InnerText;
            }
            return value;
        }

       #endregion Text Field Display

        #region Buttons
        private void evOKPS1_Click(object sender, EventArgs e)
        {//upon Ok button pressed stores IP Address and IP Port then closes window

            this.Hide();
        }

        private void evApplyPS1_Click(object sender, EventArgs e)
        {//instantly stores IP Address and IP Port but does not close window
            //Store & Apply IPaddressBox, IPportBox, ConfigPathBox
     }

        private void evCancelPS1_Click(object sender, EventArgs e)
        {//Closes the window without saving or editing information
            this.Close();
        }
        #endregion Buttons
    }
}

Open in new window

0
 
seahnaAuthor Commented:
Both code snippets worked for me.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 14
  • 8
  • 6
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now