How can I change only part of a string?

fzkim 61 Reputation points
2022-05-27T01:50:23.623+00:00

Here is a example xml.

<group>
  <value>
    <Item>1</Item>
    <Item>2</Item>
    ...
    ...
  </value>
</group>

I only want to change betweem \<value> and </value>.<br/>
For example like this.

<group>
  <value>
    &lt;Item&gt;1&lt;/Item&gt;
    &lt;Item&gt;2&lt;/Item&gt;
    ...
    ...
  </value>
</group>

I'm trying with this code.

string change = File.ReadAllText(File1Path);
change = change.Replace("<", "&lt;");
change = change.Replace(">", "&gt;");
File.WriteAllText(File1Path, change);

Thank you!

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,827 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2022-05-27T05:53:27.52+00:00

    @fzkim , Welcome to Microsoft Q&A, you could try the following code to change part of a string in the xml file.

    Code:

     XDocument doc=XDocument.Load(path);  
        var result = doc.Descendants("value").Descendants().Cast<XElement>().ToList();  
        string elestr=string.Empty;  
     
        for (int i = 0; i < result.Count(); i++)  
        {  
            StringWriter myWriter = new StringWriter();  
            elestr = result[i].ToString();  
            HttpUtility.HtmlEncode(elestr,myWriter);  
            result[i].ReplaceWith(Environment.NewLine+myWriter.ToString()+Environment.NewLine);  
        }  
        doc.Save(path);  
        string txt=File.ReadAllText(path);  
        txt = txt.Replace("&amp;", "&");  
        txt = txt.Replace("&quot;", "\"");  
        File.WriteAllText(path, txt);  
        var lines = File.ReadAllLines(path).Where(line => !String.IsNullOrWhiteSpace(line));  
        File.WriteAllLines(path, lines);  
    

    Note: Please add namespace in your app:

    using System.IO;  
    using System.Linq;  
    using System.Web;  
    using System.Xml.Linq;  
    

    Tested result:

    206114-image.png

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful