willa
willa

Reputation: 669

Open Office xml SDK exception "Cannot insert the OpenXmlElement "newChild" because it is part of a tree"

I am generating a a word document using open office sdk 2.0. I am getting an exception with is "Cannot insert the OpenXmlElement "newChild" because it is part of a tree." I am aware that is exception is due to trying duplicate nodes within the xml but I am not sure how to fix it.

private void GenerateWord(string Path)
    {
        using (WordprocessingDocument WpDoc = WordprocessingDocument.Create(Path, WordprocessingDocumentType.Document, true))
        {
            MainDocumentPart MainPart = WpDoc.AddMainDocumentPart();

            new Document(new Body()).Save(MainPart);

            Body body = MainPart.Document.Body;
            Paragraph Getskills = Test(MainPart, body);

            body.Append(Getskills);

            MainPart.Document.Save();
            WpDoc.Close();
        }
    }

    private Paragraph Test(MainDocumentPart MainPart, Body body)
    {
        Paragraph GetSkills = new Paragraph();
        string[,] ArrSkills = new string[,] { { "Live The Dream More" }, { "And Even More" } };
        List<string> SkillsList = new List<string>();

        foreach (var Item in ArrSkills)
        {
            string Skills = Item;
            SkillsList.Add(Skills);
            if (SkillsList != null)
            {
                foreach (var GetItem in SkillsList)
                {
                    GetSkills = new Paragraph(new Run(new Text(GetItem)));
                    Run BreakRun = new Run(new Break());

                    body.Append(GetSkills);
                }
            }
        }

        return GetSkills;
    }

I was just wondering if any one has come across this exception before and how they got ride of it? Thanks for any advice which you can give

Upvotes: 2

Views: 6204

Answers (1)

amurra
amurra

Reputation: 15401

You'll need to clone the node you are getting the exception with and then insert that cloned node. See this stackoverflow answer for an example.

Upvotes: 5

Related Questions