Click here to Skip to main content
15,907,913 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I'm trying to read an XML file and input the elements into separate strings. I have managed to write the elements to an array and then afterwards put then into strings but this seems like a really bad way of doing it. I'm very new to this and am just piecing together bits I find off the internet so it may all seem really badly written (which is why I'm on here):)

So a shortened version of my XML file looks a bit like this:
XML
<?xml version="1.0" encoding="utf-8" ?>
<CompanyDetails>
  <CompanyName>Companyname</CompanyName>
  <Address1>address1</Address1>
  <Address2>address2</Address2>  <!-- If no Address2 then enter NA -->>
  </CompanyDetails>


There are more elements but just one 'CompanyDetails' I thought I would be able to say "Get CompanyName and assign to string strCompanyName" then get the next element etc. This is the code I have at the moment:
C++
XmlTextReader READER = new XmlTextReader(strPath);

            while (READER.Read())
            {
                XmlNodeType NODETYPE = READER.NodeType;
                switch (NODETYPE)
                {
                    case XmlNodeType.Element:
                        if (READER.HasAttributes)
                        {
                            for (int i = 0; i < READER.AttributeCount; i++)
                            {
                                READER.MoveToAttribute(i);
                            }
                        }
                        break;
                    case XmlNodeType.Text:
                        arrStore[intCounter] = READER.Value;
                        intCounter++;

                        break;

                }
            }

            strCompanyName = arrStore[0];
            strAddress1 = arrStore[1];
            strAddress2 = arrStore[2];
            if (strAddress2 == "NA") strAddress2 = "";
            strCity = arrStore[3];
            strCounty = arrStore[4];
            strPostcode = arrStore[5];
            strTel = arrStore[6];
            strFax = arrStore[7];
            strLogo = arrStore[8];
            strSigName = arrStore[9];


So I pass through the whole thing and put all of the elements into an Array, then the final block assigns them to strings. Trouble is, the code does not recognise the data it is reading so if say address2 does not have a value, it messes up my code. Could anybody help? I'm sure XML should make it easier to read data like this. As I said before, there is only one CompanyName in the XML. I have only removed about 5 lines like city, county, postcode etc

EDIT:
C++
I tried this code but I am getting a compile error:


Error 2
The best overloaded method match for 'System.Xml.XmlNode.this[string]' has some invalid arguments

This is my code so far:
void GetXMLValues(string strFilePath)
        {
            MessageBox.Show(strFilePath);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(strFilePath);
            XmlNode node = xmlDoc.SelectSingleNode("/CompanyDetails");

            strCompanyName = node[0]; // this is the offending line, it underlines the node[0] part
}

Any suggestions?
Posted
Updated 12-Apr-11 4:23am
v2

Please read this article here on CP: Using XPathNavigator in C#[^] it tells you how to dissect an XML documnet using XPath expressions. Another good resource is found here: http://www.w3.org/TR/xpath/[^].

Happy coding!

-MRB
 
Share this answer
 
Comments
Jim607 12-Apr-11 7:29am    
I had to accept the solution below as it directly answered my query but thanks for your offered solution. The link contains some very good and easy to understand information there and I will be reading up for future use. Thanks.
You can use XPath instead of querying it like you did above. You can avoid writing those cases and make it short and simple.
XmlTextReader should be generally used if you have a huge XML file.

C#
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strPath);

//to get all the elements in the element 'CompanyName', do this :

XmlNode node= xmlDoc.SelectSingleNode("/CompanyDetails");   //specify the Xpath as "/CompanyDetails"
strCompanyName = node[0].InnerText;  // will return CompanyName node
strAddress1 = node[1].InnerText;     // will return Address1 node
//etc and then go on


If you want a specific element, lets say CompanyName,
then your XPath will be like this :
"/CompanyDetails/CompanyName"

Update : Added "InnerText" after node[0] and node[1].
 
Share this answer
 
v3
Comments
Jim607 12-Apr-11 7:28am    
That is perfect thank you. I am building a tool to make a standard email signature file. I will create a different XML for each company so I can indeed access each node individually. I did wonder about putting all companies in the same file and using a combo box to select but its easier to update this way.

Thanks again
Tarun.K.S 12-Apr-11 7:48am    
You're welcome!
Jim607 12-Apr-11 8:37am    
I tried this code but I am getting a compile error:


Error 2
The best overloaded method match for 'System.Xml.XmlNode.this[string]' has some invalid arguments

This is my code so far:
void GetXMLValues(string strFilePath)
{
MessageBox.Show(strFilePath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFilePath);
XmlNode node = xmlDoc.SelectSingleNode("/CompanyDetails");

strCompanyName = node[0]; // this is the offending line, it underlines the node[0] part
}

Any suggestions?
Tarun.K.S 12-Apr-11 10:33am    
You can check now. Use the InnerText property of the node.
Can I have this answer accepted again! :)
Jim607 13-Apr-11 7:08am    
Got it thanks:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(strFilePath);
XmlNode mynode = xmlDoc.SelectSingleNode("/CompanyDetails");
strCompanyName = mynode["CompanyName"].InnerText;

I had to enter the actual node name rather than the number, and the innertext.

Thanks again, that hacked about 25 lines of unnecessary code out of my program, and made it more reliable.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900