Click here to Skip to main content
15,888,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello!

I have a XML with data in the following format:

Original format:

XML
<root>
<body>
<sec>
<p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
<p>Text 4</p>
<p>Text 5</p>
<p>Text 6</p>
</sec>
</body>
</root>


Desired XML:
XML
<root>
<body>
<sec>
<absatz>Text 1</absatz>
<absatz>Text 2</absatz>
<absatz>Text 3</absatz>
<absatz>Text 4</absatz>
<absatz>Text 5</absatz>
<absatz>Text 6</absatz>
</sec>
</body>
</root>


My current output:
<root>
<body>
<sec>
<absatz>Text 1Text 2Text 3Text 4Text 5Text 6</absatz>
<absatz/>
<absatz/>
<absatz/>
<absatz/>
<absatz/>
</sec>
</body>
</root>


Please help.

Regards
Aman

What I have tried:

C#
var articlepara = xdoc.Element("root").Element("body").Element("sec").Elements("p").ToList();

                        foreach (var para in articlepara)
                        {
                            string paragraphvalue = para.Value;
                            xedoc.Element("artikel").Element("inhalt").Element("text").Add(new XElement("absatz"));
                            xedoc.Element("artikel").Element("inhalt").Element("text").Element("absatz").Add(paragraphvalue);
                        }
Posted
Updated 19-Jan-19 2:22am

1 solution

C#
xedoc.Element("artikel").Element("inhalt").Element("text").Add(new XElement("absatz"));
                            xedoc.Element("artikel").Element("inhalt").Element("text").Element("absatz").Add(paragraphvalue);

You create a new absatz element, but you are not using its reference to add the paragraph item. The second line will add the item to the first element that it finds with the name absatz.
 
Share this answer
 
Comments
Primo Chalice 19-Jan-19 22:47pm    
Hello!

So, is there something I am missing or do I have to rephrase the code?

Regards
Aman
Richard MacCutchan 20-Jan-19 3:27am    
You create a new element and add it into the document, but you do not keep its reference. But you need that reference in order to add the paragraph value into the correct node. So first create the new element and save its reference. Then add the paragraph value to the newly created reference, and then add the element into the document.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900