我正在处理一个具有非常嵌套结构的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Stuff>
<Item Class="Consumable">
<CalledAs>ResourceAlpha</CalledAs>
<ID>ResourceAlpha25367</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceAlpha</CalledAs>
<ID>ResourceAlpha25368</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceAlpha</CalledAs>
<ID>ResourceAlpha25371</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceAlpha</CalledAs>
<ID>ResourceAlpha25372</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceBeta</CalledAs>
<ID>ResourceBeta25376</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceBeta</CalledAs>
<ID>ResourceBeta25377</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceBeta</CalledAs>
<ID>ResourceBeta25381</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceBeta</CalledAs>
<ID>ResourceBeta25384</ID>
</Item>
<Item Class="Consumable">
<CalledAs>ResourceBeta</CalledAs>
<ID>ResourceBeta25388</ID>
</Item>
<Item Class="Construct">
<Named>ClosedFolders</Named>
<ID>ClosedFolders25393</ID>
<StorageCabinet>(102, 0, 94)</StorageCabinet>
<AssignedTo>Colonist</AssignedTo>
<Assigned Class="Consumable">
<CalledAs>ResourceBeta</CalledAs>
<ID>ResourceBeta25238</ID>
</Assigned>
</Item>
<Item Class="Construct">
<Named>ClosedFolders</Named>
<ID>ClosedFolders25394</ID>
<StorageCabinet>(105, 0, 95)</StorageCabinet>
<AssignedTo>Colonist</AssignedTo>
</Item>
<Item Class="Construct">
<Named>ClosedFolders</Named>
<ID>ClosedFolders25395</ID>
<StorageCabinet>(103, 0, 92)</StorageCabinet>
<AssignedTo>Colonist</AssignedTo>
<Assigned Class="Consumable">
<CalledAs>ResourceAlpha</CalledAs>
<ID>ResourceBeta45232</ID>
</Assigned>
</Item>
</Stuff>
</Root>
现在,我需要在Item
Stuff
类型的新元素
我正在使用纯LINQ 2 XML来处理文件:
public static XElement GetMainSaveFileAsElement()
{
if (!UtilityFunctions.CheckFileExistance())
{
return null;
}
return XElement.Load(Settings.Default.SelectedSaveFilePath);
}
// In method...
var currentSaveFile = UtilityFunctions.GetMainSaveFileAsElement();
foreach (var oneSquare in oneZone.ZoneSlabs)
{
if (oneSquare.SittingResource != null)
{
// We have a resource to add
var targetNewResource = currentSaveFile.Element("Stuff");
// Can't find any add, create or append method in targetNewResource, it's Nodes(), or Element()
}
}
我需要添加一些Item
。 Item
是一个XElement。
我在这里缺少什么?
答案 0 :(得分:1)
XElement
使用方法XElement.Add方法将内容作为子元素添加到元素:
// var content = new XElement("Item");
targetNewResource.Add(content);
还要确保将更新的元素保存回文件。