Я пытаюсь добавить объекты в файл XML. Проблема, с которой я сталкиваюсь в настоящее время, заключается в том, что она добавляет все на первый уровень. Я пытаюсь использовать список в качестве родительского элемента и элементы списка в качестве дочерних элементов.
Что я пробовал: я наткнулся на несколько сообщений, в которых используются циклы, но я не могу связать это с моим контекстом и кодом.
Код:
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 и С#, поэтому все еще пытаюсь чему-то научиться.