Xml doesn't save to file

I writing Android app in Xamarin

I have xml that is writing to file (realized)

On different Activity I try to open this file , replace some strings and save

Open file like this

var doc2 = new XmlDocument();
        var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var filePath = System.IO.Path.Combine(documentsPath, "myFile.xml");
        doc2.Load (filePath);

Replace some strings like this:

string str;
            str = doc2.OuterXml;

                str = str.Replace ("{ProductCode}", Code1);

            Console.WriteLine ("look");
            Console.WriteLine (str);

            doc2.Save (filePath);
            Console.WriteLine (doc2.OuterXml);

When I display str, I see that "ProductCode" changed.

But When I display "doc2.OuterXML" I see that it doesn't save.

This is "str":

  <Order CallConfirm="1" PayMethod="Безнал" QtyPerson="" Type="2" PayStateID="0" Remark="{Comment}" RemarkMoney="0" TimePlan="" Brand="1" DiscountPercent="0" BonusAmount="0" Department=""><Customer Login="" FIO="{FIO}" /><Address CityName="{CityName}" StationName="" StreetName="{StreetName}" House="{HouseName}" Corpus="" Building="" Flat="{FlatName}" Porch="" Floor="" DoorCode="" /><Phone Code="{Code}" Number="{Phone}" /><Products><Product Code="398" Qty="{QTY}" /><Product Code="{ProductCode1}" Qty="{QTY1}" /><Product Code="{ProductCode2}" Qty="{QTY2}" /></Products></Order>

This is doc2 after doc2.Save (filePath);:

<Order CallConfirm="1" PayMethod="Безнал" QtyPerson="" Type="2" PayStateID="0" Remark="{Comment}" RemarkMoney="0" TimePlan="" Brand="1" DiscountPercent="0" BonusAmount="0" Department=""><Customer Login="" FIO="{FIO}" /><Address CityName="{CityName}" StationName="" StreetName="{StreetName}" House="{HouseName}" Corpus="" Building="" Flat="{FlatName}" Porch="" Floor="" DoorCode="" /><Phone Code="{Code}" Number="{Phone}" /><Products><Product Code="{ProductCode}" Qty="{QTY}" /><Product Code="{ProductCode1}" Qty="{QTY1}" /><Product Code="{ProductCode2}" Qty="{QTY2}" /></Products></Order>

Why it doesn't save?

Jon Skeet
people
quotationmark

You haven't modified the document. You've asked the document for a string representation of itself, then assigned a new string to the same variable - but that doesn't change the XML in the document at all.

I would strongly urge you to use LINQ to XML (which is a nicer XML API) at which point you can have:

XDocument doc = XDocument.Load(filePath);
var query = doc.Descendants("Product")
               .Where(p => (string) p.Attribute("Code") == "{ProductCode}");
foreach (var element in query)
{
    element.SetAttributeValue("Code", Code1);
}
doc.Save(filePath);

people

See more on this question at Stackoverflow