2015-09-22 103 views
0

我试图将对象追加到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#所以仍然试图学习的东西。

回答

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

太感谢你了,那就像一个魅力!我应该尝试在XElement>。<中合并它们 – Naaz