Hello all,
I hv jst recently started using C# and i need to read some Xml documents using C#.
I hv a Xml document as ,

<?xml version="1.0" encoding="utf-16"?>
<add><
fnum>12</fnum>
<snum>12</snum>
</add>

Now, i need to independently get the values of the elements fnum and snum and sum them up and return the result in another xml file.

The code i used for this is,

public String get_XML(String xml)
        {
            String xmltext = xml;

            XmlReader textReader = XmlReader.Create(new StringReader(xmltext));

            textReader.MoveToContent();
            textReader.ReadStartElement("add");
            int fn = textReader.ReadElementContentAsInt();
            textReader.MoveToElement();
            int sn = textReader.ReadElementContentAsInt();
            int result = fn + sn;

            StringWriter sw = new StringWriter();
            XmlTextWriter textWriter = new XmlTextWriter(sw);
            textWriter.WriteStartDocument();

            textWriter.WriteStartElement("Sum", "");

            textWriter.WriteValue(result);
            textWriter.WriteEndElement();
            textWriter.WriteEndDocument();

            String x = sw.ToString();
            return x;
        }

However I get errors when I use the commands like
textReader.ReadToSibling(); , when the textReader at he position of node fum. It
doesn't move to the sibling node.
What is the error?
and also can this code be written in some other way?

This article has been dead for over six months. Start a new discussion instead.