我写了以下代码:
public static void AddUploadToXML(XDocument xdoc, int id, string fileHash, string fileName)
{
var singleUpload = new XElement("upload",
new XAttribute("backupid", id),
new XElement("file", fileHash),
new XAttribute("filename", fileName)
);
xdoc.Root.Add(singleUpload);
}
在我希望获得XML的效果中:
<uploads>
<upload backupid="3" >
<file filename=""></file>
</upload>
</uploads>
但我完成了这样的事情:
<uploads>
<upload backupid="3" filename="">
<file></file>
</upload>
</uploads>
另一个问题是:
1.如何修改应用程序其他部分的文件名属性(它将是具有给定ID的上传元素下的第一个文件元素),
2.THEN,如何添加其他文件元素,以完成这样的事情:
<uploads>
<upload backupid="3" >
<file filename="Test.001">HASHCODE</file>
<file filename="Test.002">HASHCODE2</file>
<file filename="Test.003">HASHCODE3</file>
</upload>
<upload backupid="4" >
<file filename="Test2.001">HASHCODE</file>
(...)
</upload>
</uploads>
答案 0 :(得分:0)
你需要像这样的数组对象[]
public static void AddUploadToXML(XDocument xdoc, int id, string fileHash, string fileName)
{
var singleUpload = new XElement("upload", new object[] {
new XAttribute("backupid", id),
new XElement("file", new object[] {new XAttribute("filename", fileName), fileHash})
});
xdoc.Root.Add(singleUpload);
}
答案 1 :(得分:0)
首先,您应该将方法更改为smth,如下所示:
public static void AddUploadToXML(XDocument xdoc, int id, string fileHash, string fileName)
{
var singleUpload = new XElement("upload",
new XAttribute("backupid", id),
new XElement("file", fileHash,
new XAttribute("filename", fileName))
);
xdoc.Root.Add(singleUpload);
}
至于第二个问题:你应该加载xml文件或解析xml字符串
XElement.Load(file path) / XElement.Parse(xml string)
然后你需要通过Id找到所需的“上传”节点并添加新的“文件”节点:
var element = singleUpload.Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value == "3");
element.Add( new XElement("file", "123", new XAttribute("filename", "1223")));