将子节点添加到 XElement

Adding child nodes to an XElement

我正在尝试将对象附加到 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 和 C# 的新手,所以仍在努力学习。

这应该可以解决问题:

firstRow.AddBeforeSelf(
    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()))));