【问题标题】:How to write data to XML in C# [closed]如何在 C# 中将数据写入 XML [关闭]
【发布时间】:2012-10-05 11:39:06
【问题描述】:
我是 C# 和 XML 的新手
如何将Id、name、AvailProducts 和Cost 用新值写入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】:
您可以使用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