如何在C#中将数据写入XML

时间:2012-10-05 11:39:06

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

我是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>

2 个答案:

答案 0 :(得分:1)

您可以使用XMLDocument并使用CreateNode方法。

  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

答案 1 :(得分:1)

正如其他人所说的那样,你应该首先尝试通过在谷歌搜索找到答案,甚至堆栈流本身也可能引导你。

反正

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...

}