This is my xml.
<Document>
<page no="1">
<Paragraph no="1">
<Line>line1</Line>
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
<page no="2">
<Paragraph no="1">
<Line>line1</Line>
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
</Document>
My C# code is
XmlDocument xd = new XmlDocument();
xd.Load(@"H:\Sample-8-final.xml");
XmlNodeList pnodelist = xd.GetElementsByTagName("page");
XmlNodeList xdChildNodeList = xd.ChildNodes;
for (int i = 0; i < pnodelist.Count; i++)
{
XmlNode pageNode = pnodelist[i];
foreach (XmlNode xxNode in pageNode.ChildNodes)
{
if (xxNode.Name.ToString().Trim().Equals("Paragraph"))
{
foreach (XmlNode yyNode in xxNode.ChildNodes)
{
yyNode.ParentNode.RemoveChild(yyNode);
}
}
}
xd.Save(@"H:\Sample-8-final_1.xml");
my Required output is
<Document>
<page no="1">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
</Paragraph>
</page>
<page no="2">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
</Paragraph>
</page>
</Document>
but my code produced wrong result like below:
<Document>
<page no="1">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
<page no="2">
<Paragraph no="1">
</Paragraph>
<Paragraph no="2">
<Line>line2</Line>
</Paragraph>
</page>
</Document>
Please Guide me to get out of this issue…
Use LINQ to XML to remove all descendants of the Paragraph elements:
Note: you need to put
using System.Xml.Linq;at the top of your file.