我正在用 C# 编写 Windows 窗体程序,我希望能够将信息保存到 XML 文件中。 当我第一次创建 XML 文件时,我只想能够添加声明
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
然后是我想要称为“联系人”的根节点。
最终文件应该是这样的:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Contacts>
<Contact>
<Name>name</Name>
<Address>address</Address>
<Contact>
<Contacts>
会有多个<Contact></Contact>
元素。
我遇到的问题是在我第一次创建 XML 文件时。
我的 XML 操作在它们自己的类中。 这是创建文件的方法:
public void createFile()
{
if (!File.Exists(fileName))
{
//Populate with data here if necessary, then save to make sure it exists
xmlFile = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("XML File for storing " + RootName));
xmlFile.Save(FileName);
}
}
当我尝试运行它时,我得到一个 ArgumentNullException 是未处理的错误。
关于如何实际获取文件中的数据并将其保存的任何想法? 谢谢
最佳答案
文件中需要一个根元素:
xmlFile.Add( new XElement( "Contacts" ) );
尽管您收到的错误表明发生了其他事情。也许 Filename
为空?
关于c# - 创建空白 XML 文件,然后附加到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19304930/