将字符串放入 xml 文件

Put string to xml file

我在 Xamarin (c#) 上编写 Android 应用程序

我xml正在写入文件

XML:

<Order 
    CallConfirm="1"
    PayMethod="Безнал" 
    QtyPerson="2" 
    Type="2" 
    PayStateID="0" 
    Remark="111111" 
    RemarkMoney="0" 
    TimePlan="" 
    Brand="1" 
    DiscountPercent="0" 
    BonusAmount="0"
    Department="">
       <Customer Login="dev.bohdan@gmail.com" FIO="Bohdan Trachuk"/>
       <Address 
          CityName="Київ" 
          StationName="" 
          StreetName="" 
          House="" 
          Corpus="" 
          Building="" 
          Flat="" 
          Porch="" 
          Floor="" 
          DoorCode=""/>         
       <Phone Code=" (0" Number="96) 717-19-02" />
       <Products/>
</Order>

我需要将这个字符串 <Product Code="{ProductCode}" Qty="{QTY}" /> 放入 <Products> </Products> 块中。然后更改 {ProductCode}{QTY} 值。

如何更改我知道并且有代码。 像这样

XDocument doc = XDocument.Load(filePath);

var query = doc
    .Descendants("Product")
    .Where(p => (string) p.Attribute("Qty") == "{QTY}");

foreach (var element in query)
{
    element.SetAttributeValue("Qty", counttext.Text);
}

var query2 = doc
    .Descendants("Product")
    .Where(p => (string) p.Attribute("Code") == "{ProductCode}");

foreach (var element in query2)
{
    element.SetAttributeValue("Code", Code1);
}

如何将字符串直接放入此块?

使用正确的值为您的 <Product> 创建一个 XElement 节点,然后添加它会容易得多,而不是添加它,然后搜索您刚刚添加的节点以替换它的价值观。因此:

var product = new XElement("Product", new XAttribute("Code", Code1), new XAttribute("Qty", counttextText));
var products = doc.Descendants("Products").First(); // Get the first Products node.  Throw an exception if not found.
products.Add(product);

示例 fiddle.