Adding child nodes to an XElement

岁酱吖の 提交于 2019-12-12 00:25:11

问题


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.

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:

<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.


回答1:


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


来源:https://stackoverflow.com/questions/32707644/adding-child-nodes-to-an-xelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!