本文介绍了如何在C#4.0中删除指定xmlnode的所有子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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>

我的C#代码是

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");

我的必需输出为

<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...

推荐答案

使用LINQ to XML删除Paragraph元素的所有后代:

Use LINQ to XML to remove all descendants of the Paragraph elements:

XElement root = XElement.Load(@"H:\Sample-8-final_1.xml");
root.Descendants("Paragraph").Descendants().Remove();

注意:您需要使用System.Xml.Linq放入在文件顶部。

Note: you need to put using System.Xml.Linq; at the top of your file.

这篇关于如何在C#4.0中删除指定xmlnode的所有子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 16:56
查看更多