Reputation: 83
i've been searching and trying for hours but i can't make it work. so i decided to ask a question here. kindly help me.
i have an xml something like this
<parent>
<anothertag/>
<body>
<monitor value="3"/>
<mouse value="5"/>
<chair>
<monoblock value="5"/>
</chair>
</body>
</parent>
and this is my desired xml output if possible
<parent>
<anothertag/>
<body>
<anotherbody>
<monitor value="3"/>
<mouse value="5"/>
<chair>
<monoblock value="5"/>
</chair>
</anotherbody>
</body>
</parent>
this is my code
string xml = "<parent>" +
"<anothertag/>" +
"<body>" +
"<monitor value=\"3\"/>" +
"<mouse value=\"5\"/>" +
"<chair>" +
"<monoblock value=\"5\"/>" +
"</chair>" +
"</body>" +
"</parent>";
XDocument doc = XDocument.Parse(xml);
var p = doc.Descendants("body").Elements();
foreach (var item in doc.Descendants("body").ToList())
{
item.Add(new XElement("anotherbody", p));
}
Console.WriteLine(doc.ToString());
and here is the output
<parent>
<anothertag />
<body>
<monitor value="3" />
<mouse value="5" />
<chair>
<monoblock value="5" />
</chair>
<anotherbody>
<monitor value="3" />
<mouse value="5" />
<chair>
<monoblock value="5" />
</chair>
</anotherbody>
</body>
</parent>
the output is redundant. how do i remove it?
the p.Remove();
remove all the elements. thank you
Upvotes: 1
Views: 76
Reputation: 1109
I think the problem is that in this line
var p = doc.Descendants("body").Elements();
you should not be extracting the .Elements()
from your descendants. Change the line to
var p = doc.Descendants("body");
and it should work. But keep in mind that .Descendants()
will find all of the tags that match the name specified even if they are nested inside other tags.
This may be ok if the tag <body>
only appears as a child of <parent>
, if not it would be better to rewrite the line in question as follows
var p = doc.Elements("body");
Upvotes: 0
Reputation: 556
Try this
foreach (var item in doc.Descendants("body").ToList())
{
item.ReplaceAll(new XElement("anotherbody", item.Nodes()));
}
Upvotes: 3