• 0

[VS C#] Reading a string from XML


Question

Hey,

I am trying to read string (<skins>whiteaero.png</skins>) from the xml file.

XML file:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;Settings&gt;
  &lt;username&gt;nothing to see&lt;/username&gt;
  &lt;password&gt;nothing to see&lt;/password&gt;
  &lt;server&gt;nothing to see&lt;/server&gt;
  &lt;port&gt;nothing to see&lt;/port&gt;
  &lt;isactive&gt;1&lt;/isactive&gt;
  &lt;skins&gt;whiteaero.png&lt;/skins&gt;
&lt;/Settings&gt;

Here is the code I am using:

       private void alert_Load(object sender, EventArgs e)
        {

            XmlTextReader reader = new XmlTextReader("settings.xml");

            reader.ReadStartElement();

            string sk = reader.ReadElementString("skin");

            reader.Close();

How would I make it read line 8 (<skins>whiteaero.png</skins>) of the XML file?

Thanks.

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

I think you would need to do something like this...

XmlTextReader reader = new XmlTextReader("settings.xml");
bool elementFound = false;
while(reader.Read() &amp;&amp; !elementFound)
{
if(reader.Name == "skin")
{
reader.Value
elementFound = true;
}
}
reader.Close();

Link to comment
Share on other sites

  • 0

A simple function I wrote for this particular problem:

private string readXml(string tag, string filename)
 {
 ?	XmlTextReader theme_file = new XmlTextReader(filename);

 ?	while(!theme_file.EOF)
 ?	{
 ? ?theme_file.Read();
 ? ?if(theme_file.IsStartElement() &amp;&amp; theme_file.Name==tag)
 ? ?{
 ? ?	string result = theme_file.ReadString();
 ? ?	theme_file.Close();
 ? ?	return result;
 ? ?}
 ?	}

 ?	return "error";
 }

So if you want to read the element named "test" in file "C:\text.xml" you just use it like this:

string str_Test = readXml("test", "C:\text.xml");

Link to comment
Share on other sites

  • 0

Instead of making a new topic, I am going to post new question here.

I want to write a new string (new line even) to current xml file instead of creating a new xmldocument. Will it be the same way as reading?

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.