Я пытаюсь добавить объекты в файл XML. Проблема, которую я сейчас имею, заключается в том, что она добавляет все на первом уровне. Я пытаюсь иметь список как родительский элемент и элементы списка как дочерние элементы.Добавление дочерних узлов в XElement
Что я пробовал: Я столкнулся с несколькими сообщениями, где они используют циклы, но я не могу связать это с моим контекстом и кодом.
Код:
XDocument xDocument = XDocument.Load(@"C:\Users\hci\Desktop\Nazish\TangramsTool\TangramsTool\patterndata.xml");
XElement root = xDocument.Element("Patterns");
foreach (Pattern currentPattern in PatternDictionary.Values)
{
String filePath = currentPattern.Name.ToString();
IEnumerable<XElement> rows = root.Descendants("Pattern"); // Returns a collection of the descendant elements for this document or element, in document order.
XElement firstRow = rows.First(); // Returns the first element of a sequence.
if (currentPattern.PatternDistancesList.Count() == 9)
{
firstRow.AddBeforeSelf(//Adds the specified content immediately before this node.
new XElement("Pattern"),
new XElement("Name", filePath.Substring(64)),
new XElement("PatternDistancesList"),
new XElement("PatternDistance", currentPattern.PatternDistancesList[0].ToString()),
new XElement("PatternDistance", currentPattern.PatternDistancesList[1].ToString()),
}
}
Текущий XML файла:
<Pattern/>
<Name>match.jpg</Name>
<PatternDistancesList/>
<PatternDistance>278</PatternDistance>
<PatternDistance>380</PatternDistance>
То, что я хотел бы как конечный результат:
<Pattern>
<Name>match.jpg</Name>
<PatternDistancesList>
<PatternDistance>278</PatternDistance>
<PatternDistance>380</PatternDistance>
</PatternDistancesList>
<Pattern/>
Любые советы будут оценены. Я новичок в WPF и C#, так что все еще пытаюсь научиться вещам.
Спасибо так много, что работает как шарм! Я должен был попытаться объединить их в XElement>. < – Naaz