Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I've gotten most of it down, in the fact that I can read EVERY value, all at once.

The problem, is how the XML file is setup (which I can not change, as that is how the application it is for uses it)


F.E.
XML
<ServerSettings>
  <property name="ServerPort" value="25000"/>
  <property name="ServerIsPublic" value="true"/>
  <property name="ServerName" value="My Game Host"/>
  <property name="ServerPassword" value=""/>
  <property name="ServerMaxPlayerCount" value="4"/>
</ServerSettings>  


There are more values and such, but this is just an example. I need to get my application to write the values to textboxes.


Here is my code, which could probably use some improvements. Thank you!

C#
using (XmlReader prereader = XmlReader.Create(presetlocation)) // This variable is declared after selecting the xml preset file with OpenFileDialog // 
{
    while (prereader.Read())
    {
        if (prereader.IsStartElement())
        {
	    switch (prereader.Name)
            {
	      case "ServerSettings":
		break;
              case "property":
		string attribute = prereader["name"];
		string attribute2 = prereader["value"];
		if (attribute != null)
		{
		// This was writing the data to a txt to test the reading. It came up with strange results //
			    				
		    FileStream fs1 = new FileStream("D:\\TEST.txt", FileMode.OpenOrCreate, FileAccess.Write);
		    StreamWriter writer = new StreamWriter(fs1);
		    writer.Write(attribute + " " + attribute2);
		    writer.Close();
		}
		break;
	    }
	}
    }
}
Posted
Updated 17-Dec-13 6:49am
v2

Please see my short overview of the approaches to XML parsing offered by .NET FCL:
  1. Use System.Xml.XmlDocument class. It implements DOM interface; this way is the easiest and good enough if the size if the document is not too big.
    See http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx[^].
  2. Use the class System.Xml.XmlTextReader; this is the fastest way of reading, especially is you need to skip some data.
    See http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx[^].
  3. Use the class System.Xml.Linq.XDocument; this is the most adequate way similar to that of XmlDocument, supporting LINQ to XML Programming.
    See http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx[^], http://msdn.microsoft.com/en-us/library/bb387063.aspx[^].


—SA
 
Share this answer
 
I fixed the problem. Instead of just searching for ALL properties that don't equal null, I made it so it only searches for certain text.

Instead of

C#
if (attribute != null)



It is now

C#
if (attribute == "ServerPort")



Sorry for the stupid question :)
 
Share this answer
 

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