将子节点添加到XElement

时间:2015-09-22 02:56:44

标签: c# wpf 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#的新手,所以还在努力学习。

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

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