向XElement添加子节点

本文关键字:子节点 添加 XElement | 更新日期: 2023-09-27 18:13:55

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

向XElement添加子节点

这应该能奏效:

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()))));