locked
How to remove table tag based on condition using LINQ? RRS feed

  • Question

  • User-1148373670 posted

    I have below XML file that contains some data in table format.

    <Name>

    <p id="P.01.0001">First Text</p>

    <p id="P.01.0002">First Text</p>

    <p id="P.01.0003">First Text</p>

    <Table id="T.01.0001">

    <tr>

    <td></td>

    </tr>

    <tr>

    <td></td>

    </tr>

    </Table>

    <p id="P.01.0001">First Text</p>

    <p id="P.01.0002">First Text</p>

    <p id="P.01.0003">First Text</p>

    <Table id="T.01.0002">

    <tr>

    <td></td>

    </tr>

    <tr>

    <td></td>

    </tr>

    <tr>

    <td></td>

    </tr>

    <tr>

    <td></td>

    </tr>

    <tr>

    <td></td>

    </tr>

    <tr>

    <td></td>

    </tr>

    </Table>

    </Name>

    I want to remove table tag from xml if table row is greater than 3 else I want to keep it as it is. I above senario, I want to remove only bold mark table

    Please provide some LINQ query to get the row count first and based on count remove the complete table for XML.

    Thanks in advance

    Tuesday, November 4, 2014 8:08 AM

Answers

  • User1918509225 posted

    Hi info2ambrish,

    For your issue,I wrote a demo for in linq to xml.

    First ,you need to get the all the element  named"Table",the n you need to iterate the

    Elements to get the count of "tr",if it is more than 3,you can remove it .

    Please try  the code below:

    XElement ex = XElement.Load(Server.MapPath("FileName.xml"));            
    IEnumerable<XElement> q = from ele in ex.Elements("Table")
                                          select ele;
                foreach (XElement x in q) {
                    int count = x.Elements("tr").Count();
                    if (count >= 3) {
                        x.Remove();
                    }
                }
    
                ex.Save(Server.MapPath("FileName.xml"));
    

    Best Regards,

    Kevin Shen.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 5, 2014 10:03 PM