将tbody XML元素添加到XDcoument中的表元素

时间:2016-05-02 21:18:06

标签: c# .net xml xml-parsing linq-to-xml

如果在Xdcoument上丢失,则要在<table>元素中添加<table class="newtable" id="item_559_Table1" cellpadding="0" cellspacing="0" data-its-style="width:11.4624em; border-spacing:0;"> <colgroup data-its-style="width:11.4624em; " /> <tr> <td data-its-style="padding:0.2292em; vertical-align:top; "> <p data-its-style="">My dad cooks up a pot of chicken soup, and</p> </td> </tr> <tr> <td data-its-style="padding:0.2292em; vertical-align:top; "> <p data-its-style="font-weight:normal; ">This cold means I can’t taste a thing today!</p> </td> </tr> </table> 元素。

<table class="newtable" id="item_559_Table1" cellpadding="0" cellspacing="0" data-its-style="width:11.4624em; border-spacing:0;">
        <colgroup data-its-style="width:11.4624em; " />
<tbody>
        <tr>
            <td data-its-style="padding:0.2292em; vertical-align:top; ">
                <p data-its-style="">My dad cooks up a pot of chicken soup, and</p>
            </td>
        </tr>
        <tr>
            <td data-its-style="padding:0.2292em; vertical-align:top; ">
                <p data-its-style="font-weight:normal; ">This cold means I can’t taste a thing today!</p>
            </td>
        </tr>
</tbody>
    </table>

输出应该看起来像

*

**不寻找XSLT解决方案。

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是抓住<table>的孩子,然后按照你想要的方式添加它们。

var doc = XDocument.Load("file.xml");

var colgroup = doc.Root.Elements("colgroup");
var tr = doc.Root.Elements("tr");

// Add tr to tbody
var tbody = new XElement("tbody", tr);

// Replace the children of table with colgroup and tbody
doc.Root.ReplaceNodes(colgroup, tbody);