我是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>
答案 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);
答案 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...
}