我正在尝试将一些数据写入XML文件。 实际上,我可以这样做,但在每次运行中,XML文件都会被覆盖,而我希望它添加另一行。 这是我到目前为止所做的:
public static void StoreCustomerIntoXML(string Id)
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Customers\\CustomersListCreated.xml";
XmlDocument xmlDoc = new XmlDocument();
XmlNode rootNode = xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(rootNode);
XmlNode userNode = xmlDoc.CreateElement("Id");
userNode.InnerText = Id;
rootNode.AppendChild(userNode);
xmlDoc.Save(reportPath);
}
因此,首次调用该方法将包括Id = 1234 第二轮将包括Id = 6543 XML文件将始终包含上次运行的ID,仅包含此Id。
答案 0 :(得分:2)
试试这个
public static void StoreCustomerIntoXML(string Id)
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "CustomersListCreated.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(reportPath))
{
xmlDoc.Load(reportPath);
XmlNode rootNode = xmlDoc.DocumentElement;
xmlDoc.AppendChild(rootNode);
XmlElement elem = xmlDoc.CreateElement("Id");
elem.InnerText = Id;
rootNode.AppendChild(elem);
}
else
{
XmlNode rootNode = xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(rootNode);
XmlNode userNode = xmlDoc.CreateElement("Id");
userNode.InnerText = Id;
rootNode.AppendChild(userNode);
}
xmlDoc.Save(reportPath);
}
答案 1 :(得分:0)
您可以检查文件是否存在并使用方法Load加载它,而不是每次调用方法时都创建一个新文件。
public static void StoreCustomerIntoXML(string Id)
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Customers\\CustomersListCreated.xml";
XmlDocument xmlDoc;
if (File.Exists(reportPath))
xmlDoc = XDocument.Load(reportPath);
else
xmlDoc = new XmlDocument();
XmlNode rootNode = xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(rootNode);
XmlNode userNode = xmlDoc.CreateElement("Id");
userNode.InnerText = Id;
rootNode.AppendChild(userNode);
xmlDoc.Save(reportPath);
}
答案 2 :(得分:0)
public static void StoreCustomerIntoXML(string Id)
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Customers\\CustomersListCreated.xml";
XmlDocument xmlDoc = new XmlDocument();
XmlNode rootNode;
if (File.Exists(reportPath))
{
xmlDoc.Load(reportPath);
rootNode = xmlDoc.DocumentElement;
}
else
{
rootNode = xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(rootNode);
}
XmlNode userNode = xmlDoc.CreateElement("Id");
userNode.InnerText = Id;
rootNode.AppendChild(userNode);
xmlDoc.Save(reportPath);
}