簡體   English   中英

XML不保存到文件

[英]Xml doesn't save to file

我在Xamarin中編寫Android應用

我有正在寫入文件的xml(已實現)

在其他活動上,我嘗試打開此文件,替換一些字符串並保存

像這樣打開文件

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);

像這樣替換一些字符串:

string str;
            str = doc2.OuterXml;

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

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

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

當顯示str時,我看到“ ProductCode”已更改。

但是,當我顯示“ doc2.OuterXML”時,我看到它沒有保存。

這是“ 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>

doc2.Save (filePath);之后是doc2 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>

為什么不保存?

您尚未修改文檔。 您已經要求文檔提供其自身的字符串表示形式,然后將新字符串分配給相同的變量-但這根本不會改變文檔中的XML。

我強烈建議您使用LINQ to XML(這是更好的XML API),此時您可以:

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);

你錯過了一條線

doc2.OuterXml = str;

您的代碼是OuterXml中的str

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

那么您替換了str值而不是doc2值,因此它保持不變。 所以現在您需要添加

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

doc2.OuterXml = str;

現在您將看到doc2.OuterXml也將為您提供相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM