2

Below is my sample XML file stored in the server ;

<exam>
  <name>Maths</name>
  <percentage>100</percentage>
</exam>
<exam>
  <name>Physics</name>
  <percentage>70</percentage>
</exam>
<exam>
  <name>Chemistry</name>
  <percentage>70</percentage>
</exam>

I have another table as mentioned below

Name of Exam                            Percentage
Maths                                       50
Physics                                     60
Chemistry                                   70

What I need here is that I need to read this XML File and replace the percentage value in the XML file based on the table that I have. I have more than 75 tags for exam

I have used the below logic of hardcoding everything but I am not sure if my logic would be good

    public static void Changepercentage()
    {
        try{

            string xmlpercentage= Loaddefault.xmlpercentage;

            string f = xml
            List<string> lines = new List<string>();

            // 2
            // Use using StreamReader for disposing.
            using (StreamReader r = new StreamReader(f, System.Text.Encoding.Default))
            {
                // 3
                // Use while != null pattern for loop
                string line;

                while ((line = r.ReadLine()) != null)
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(line, "<exam>Maths</exam>"))
                    {
                        lines.Add(@"" + line + "");
                        line = "<percentage>50</percentage>";
                    }                       
                }
            }


            System.IO.File.WriteAllLines(xmlpercentage, lines.ToArray());

            Logger.Instance.InfoLog("Successfully updated the percentage.xml file");
        }
        catch (Exception ex)
        {

            Logger.Instance.ErrorLog("Problem in updating the percentage.xml file :"+ ex.Message);
            throw new Exception("Problem in updating the percentage.xml file");
        }

    }
5
  • 1
    Okay, so how far have you got? I would suggest using LINQ to XML for all of this - it's a very pleasant XML API. What is the format of your table? Is it a text file, or in a database, or something else? Do you already have code to work with that? Basically, you've asked a fairly broad question at the moment with no indication of what you've tried or what specific problem you've got. Commented May 12, 2016 at 6:28
  • I have code to read the data from that table. I need logic only to read the XML file and replace the percentage values. Commented May 12, 2016 at 6:31
  • I have updated what I have got but I am not sure if that is the right way to proceed. Commented May 12, 2016 at 6:37
  • No, it absolutely isn't. You're trying to manipulate XML, so use an XML API as I said in the first comment. Commented May 12, 2016 at 6:38
  • This answer link will be also useful.. stackoverflow.com/a/1487764/1660178 Commented May 12, 2016 at 6:44

2 Answers 2

1

You can use this documentation

//Make sure that the project references the System.Xml namespace.
//Use the Imports statement on the Xml namespace

using System.Xml;

//Create a new XmlDocument class, and use the Load method to load it.

XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load ("test.xml");

//Iterate through the children of the document element, and find all the "percentage" nodes. and update it.

foreach(XmlNode node1 in node.ChildNodes)
   foreach (XmlNode node2 in node1.ChildNodes)
      if (node2.Name == "percentage")
         {
            Decimal percentage = 60;//your new percentage
            node2.InnerText = percentage;
          }

//Use the Save method of the XmlDocument class to save the altered XML to a new file that is named test1.xml.         

myXmlDocument.Save("test1.xml");
Sign up to request clarification or add additional context in comments.

4 Comments

This is much more convoluted than the equivalent LINQ to XML would be.
I think it is much basic implementation. And that article has been archived...but it will be works
Yes, it will work - but why provide a complex approach when there are simpler ones with more modern APIs? Would you give an answer using ArrayList rather than List<T>?
@JonSkeet Yes you are absolutely right...I have no argument to you...I am fan of you.You are my role model for the programming.
0

Iterate over all <exam> nodes of your XML, read the child node <name>. With the InnerText of name query the data base and put the data base result into the <percentage> node.

Something like this should do:

var doc = XDocument.Parse(yourXml);
foreach(XElement exam in doc.Descendants("exam"))
{
    var examName = exam.Descendants("name").First().Value;
    var newPercentage = GetPercentage(examName);
    exam.Descendants("percentage").First().Value = newPercentage;
}

1 Comment

Note that a simpler way of getting the first child element with a particular name is to just use Element("foo"). I'd also use the explicit conversions, e.g. var examName = (string) exam.Element("name");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.