【问题标题】:How to write data to XML in C# [closed]如何在 C# 中将数据写入 XML [关闭]
【发布时间】:2012-10-05 11:39:06
【问题描述】:

我是 C# 和 XML 的新手

如何将IdnameAvailProductsCost 用新值写入C# 中的XML 文件?

 <root>
<Bathing>
    <Id>San100</Id>
    <name>Santoor</name>
    <AvailProducts>30</AvailProducts>
    <Cost>20.00</Cost>
</Bathing>
<Bathing>
    <Id>Det123</Id>
    <name>Dettol</name>
    <AvailProducts>30</AvailProducts>
    <Cost>15.00</Cost>
</Bathing>
<Bathing>
    <Id>Rex123</Id>
    <name>Rexona</name>
    <AvailProducts>30</AvailProducts>
    <Cost>16.00</Cost>
</Bathing>
</root>

【问题讨论】:

标签: c# .net xml linq-to-xml


【解决方案1】:

正如其他人所说,您应该首先尝试通过在 Google 中搜索来找到答案,甚至 stackflow 本身可能已经指导了您。

不管怎样,

XmlDocument xDoc = new XmlDocument(); 
xDoc.Load("XMLFile.xml")");  
XmlNodeList nodeList; 
nodeList = xDoc.DocumentElement.SelectNodes("Bathing");

foreach (XmlNode node in nodeList)

{

XmlNode child = node.SelectSingleNode("Id");

child.InnerText = "NewValue";

..write for other child nodes...

} 

【讨论】:

    【解决方案2】:

    您可以使用XMLDocumentCreateNode 方法。

      XmlDocument doc = new XmlDocument(); 
    
      doc.LoadXml(); // file path of the XML you provided in your question.
    
      XmlNode nameElem = doc.CreateNode("element", "Name", "");  
      nameElem.InnerText = "Darren Davies";
    
      XmlNode availableProducts = doc.CreateNode("element", "AvailProducts", "");  
      availableProducts.InnerText = "Product";
    
      XmlNode cost = doc.CreateNode("element", "Cost", "");  
      cost.InnerText = "Cost";
    
      XmlElement root = doc.DocumentElement;
    
      root.AppendChild(nameElem); // Append the new name element
      root.AppendChild(availableProducts);
      root.AppendChild(cost);
    

    http://msdn.microsoft.com/en-us/library/ms162365.aspx#Y1700

    【讨论】:

    • 将添加新节点,我认为要求是保存现有节点的新值。
    猜你喜欢
    • 1970-01-01
    • 2013-10-09
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    相关资源
    最近更新 更多