我有一个XML文件:
<uploads>
<upload backupid="3">
XXXXXXXXX
</upload>
</uploads>
如何添加元素(甚至更多)来代替XXX
(对于给定的backupid
)?
<file filename="XXX">HASH-CODE</file>
我已尝试过以下内容:
public static void AddFileToExistingUpload(int lastUsedID, string fileName, string generatedHash)
{
var xdoc = LoadUploadsXML();
var element = xdoc.Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));
element.Add(new XElement("file", generatedHash, new XAttribute("filename", fileName)));
SaveUploadXML(xdoc);
}
但我得到的只是:
未处理的类型&#39; System.NullReferenceException&#39; 发生
答案 0 :(得分:1)
xdoc
只有一个uploads
元素,upload
位于其中:
var element = xdoc.Element("uploads").Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));
或插入Root
代替:
var element = xdoc.Root.Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));
或使用Descendants
:
var element = xdoc.Descendants("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));