none
C# Using.IO.File to replace a element within a XML file. RRS feed

  • Question

  • Hello everyone, I am new to software developing and been using visual studio for about 5 months but I have been set a task to modify a xml document using IO.File.

    I havent got any code for this because everything I have tried or looked at does not work at all. I have looked at MSDN for some help but I cannot find anything in order to perform my operation.

    I can use Xpath to change an elements value but I need to use IO.File.

    Does anyone know of way to do this?

    Thank you for your time.

    regards

    Dan

    Wednesday, February 7, 2018 3:05 PM

Answers

  • Hi everyone, The issue is now solved. Here is my code and it works fine :)

    Thank you to everyone who has helped me. Thank god for you super developers.

     public static void Dictionary1()
    {
      Dictionary<string, string> dictionary = new Dictionary<string, string>();
      dictionary.Add("{{name}}", "dan");
      dictionary.Add("{{work}}", "software");
      dictionary.Add("{{car}}", "honda");
      dictionary.Add("channel", "2");
    
      StringBuilder stringBuilder = new StringBuilder();
    
    foreach(KeyValuePair<string, string> entry in dictionary)  {
     stringBuilder.AppendLine(entry.Key + "," + entry.Value);
                    
      if (entry.Key.StartsWith("{{"))
       {
        stringBuilder.Replace(entry.Key, entry.Value);
       }
    }
    
    File.WriteAllText(@"C:\EDchannel2\EDchannelTemplate.txt", stringBuilder.ToString());
    
       string channel = dictionary["channel"];
       string outputFile = @"C:\EDchannel2\EDchannel" + channel + ".txt";
       File.WriteAllText(outputFile, stringBuilder.ToString());
    
    }



    Dan Boddington


    • Edited by DanBod85 Tuesday, February 27, 2018 9:15 AM
    • Marked as answer by DanBod85 Tuesday, February 27, 2018 9:20 AM
    Tuesday, February 27, 2018 9:14 AM

All replies

  • You won't be using IO.File. You'll likely want to look at using XDocument. There are plenty of examples available using XDocument to modify XML files. The official docs with examples are here.

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, February 7, 2018 3:28 PM
    Moderator
  • If you can explain why you must use IO.File then perhaps someone can help you with that.

    Without mode details I must say that XML is not designed to be used that way. You should read the entire file then change the data and write it back out or read the file from beginning to end and write it out while reading it and then change the data when necessary. Something like that.



    Sam Hobbs
    SimpleSamples.Info

    Thursday, February 8, 2018 4:44 AM
  • It's a silly requirement to use IO.File. But it might be for learning.

    1. Read the file.
    2. Search for the node. You might want to break it down; search for node, search node for child node, search child node for other child node etc. You can use the IndexOf method of the string class.
    3. Do whatever needs to be done.
    4. Back to (2) if needed.
    5. Save the file.

    • Edited by sterretje_K5 Thursday, February 8, 2018 5:43 AM Addedd step 5
    Thursday, February 8, 2018 5:42 AM
  • But it might be for learning.

    Then the lesson is to not do it. The best teacher would guide the student in a more productive direction.


    Sam Hobbs
    SimpleSamples.Info

    Thursday, February 8, 2018 6:15 AM
  • Hi Sam, thank you for the reply. I have to use IO.File for training purposes. I know its not the best way to do this but I have to what i am told unfortunitly. I know that there plenty of other ways to do it but I am just really struggleing to do the job this way. Just seems like too much messing around.
    Thursday, February 8, 2018 7:42 AM
  • Thank you sterretje_K5, I know it is a silly requirement but orders are orders and it is for training purposes. Thank you for your advice. I shall give that a try.

    Thursday, February 8, 2018 7:47 AM
  • Thank you Michael for your help and support. Unfortunately I have to use IO.File for training purposes otherwise I would have done it a much simpler way. Its a pain in the backside but hey thats what being a developer is all about right :)
    Thursday, February 8, 2018 7:51 AM
  • I completley agree with you Sam.
    Thursday, February 8, 2018 8:08 AM
  • Thank you Michael for your help and support. Unfortunately I have to use IO.File for training purposes otherwise I would have done it a much simpler way. Its a pain in the backside but hey thats what being a developer is all about right :)

    Not sure I quite agree with this statement!

    Personally I would respectfully point out that the File class is the wrong tool to amend XML files and would, in a realistic situation, create difficult to maintain code that would be harder to understand later on and therefore have an increased chance of leading to bugs.

    Nevertheless, I think the only thing you could do with the File class is simply read in the XML as text, do what you need to do and then write it back out (since the File class is, obviously, only designed to deal with file handling and doesn't really have any useful XML-related functionality):

    string allXML = File.ReadAllText(myXMLfilePath);
    
    // amend allXML with string handling, e.g. String.Replace()
    
    File.WriteAllText(myXMLfilePath, allXML);

    Thursday, February 8, 2018 8:24 AM
  • Thank you RJP1973, I do not really agree with the statement either. I have only been using C# for 5 months but even I know there are much better ways to modify an XML document. I can fix the problem by using Xpath which works well but IO.File is a little bit more messy and as you said, incresased chances of bugs.

    Thank you very much for your example, I am trying a few things out and I will add your example to the list to try out.

    Thank you.

    Thursday, February 8, 2018 9:32 AM
  • Hello DanBod85,

    If you want to parse the xml document use IO, the process will be more related to data structure and algorithm. and you could refer source code of XmlTextReader, which is basic parse process.

    http://referencesource.microsoft.com/#System.Xml/System/Xml/Core/XmlTextReaderImpl.cs,15e64463218efb02

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, February 8, 2018 10:58 AM
    Moderator
  • Thank you for your help Neil.

    I shall take a look at the link.

    Thursday, February 8, 2018 12:09 PM
  • You didn't mention the specific requirements for using File so there are plenty of ways to do this for training purposes. Using File you can read the file into memory using ReadAllText. Then use XDocument to parse the string. 

    Alternatively you can use File.OpenRead to get a FileStream. Or use File.OpenText to get a StreamReader. Then use XmlReader to read the XML.


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, February 8, 2018 2:41 PM
    Moderator
  • Hello DanBod85,

    Is there any update or any other assistance I could provide? You could mark the helpful reply as answer if the issue has been solved. And if you have any concerns, please do not hesitate to let us know.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 27, 2018 8:55 AM
    Moderator
  • Hi Neil, Yes the answer is now solved, I was just about to upload my code to show everyone what I have done. :)

    Dan Boddington

    Tuesday, February 27, 2018 9:09 AM
  • Hi everyone, The issue is now solved. Here is my code and it works fine :)

    Thank you to everyone who has helped me. Thank god for you super developers.

     public static void Dictionary1()
    {
      Dictionary<string, string> dictionary = new Dictionary<string, string>();
      dictionary.Add("{{name}}", "dan");
      dictionary.Add("{{work}}", "software");
      dictionary.Add("{{car}}", "honda");
      dictionary.Add("channel", "2");
    
      StringBuilder stringBuilder = new StringBuilder();
    
    foreach(KeyValuePair<string, string> entry in dictionary)  {
     stringBuilder.AppendLine(entry.Key + "," + entry.Value);
                    
      if (entry.Key.StartsWith("{{"))
       {
        stringBuilder.Replace(entry.Key, entry.Value);
       }
    }
    
    File.WriteAllText(@"C:\EDchannel2\EDchannelTemplate.txt", stringBuilder.ToString());
    
       string channel = dictionary["channel"];
       string outputFile = @"C:\EDchannel2\EDchannel" + channel + ".txt";
       File.WriteAllText(outputFile, stringBuilder.ToString());
    
    }



    Dan Boddington


    • Edited by DanBod85 Tuesday, February 27, 2018 9:15 AM
    • Marked as answer by DanBod85 Tuesday, February 27, 2018 9:20 AM
    Tuesday, February 27, 2018 9:14 AM
  • Hello DanBod85,

    You could close thread by marking your reply as answer. This also can be beneficial to other community members reading this thread.  :)

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 27, 2018 9:18 AM
    Moderator
  • All done. Thank you

    Dan Boddington

    Tuesday, February 27, 2018 9:21 AM