wpf 将子节点添加到 XElement

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32707644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:25:52  来源:igfitidea点击:

Adding child nodes to an XElement

c#wpfxelement

提问by Naaz

I am trying to append objects into an XML file. The problem I currently have is it appends everything at the first level itself. I am trying to have the list as the parent element and list items as the child elements.

我正在尝试将对象附加到 XML 文件中。我目前遇到的问题是它在第一级本身附加了所有内容。我试图将列表作为父元素,将列表项作为子元素

What I've tried: I came across a few posts where they use loops but I am unable to relate that to my context and code.

我尝试过的:我遇到了一些他们使用循环的帖子,但我无法将其与我的上下文和代码联系起来。

Code:

代码:

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()),
     }
}

Current XML File:

当前 XML 文件:

<Pattern/> 
<Name>match.jpg</Name> 
<PatternDistancesList/>       
<PatternDistance>278</PatternDistance>
<PatternDistance>380</PatternDistance> 

What I would like as the end result:

我想要的最终结果是:

<Pattern> 
<Name>match.jpg</Name> 
<PatternDistancesList>       
    <PatternDistance>278</PatternDistance>
    <PatternDistance>380</PatternDistance>
</PatternDistancesList> 
<Pattern/>

Any tips will be much appreciated. I'm new to WPF and C# so still trying to learn things.

任何提示将不胜感激。我是 WPF 和 C# 的新手,所以仍在努力学习。

回答by MarcinJuraszek

This should do the trick:

这应该可以解决问题:

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