C#在不知道父节点的情况下,根据内部文本删除XML节点

时间:2018-10-24 15:41:12

标签: c# xml

我有一个结构如下的文档,并且我试图删除所有出现的“ DELETE ME”。其背后没有XPath模式。最好的方法是什么?

原始XML在下面。

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
  <PageInfo>
   <ID>0</ID>
   <NUM>DELETE ME</NUM>
   <URL>er.php</URL>
  </PageInfo>
  <SomeOtherAttributeName>
   <ID>1</ID>
   <NUM> 
       <INDX>DELETE ME</INDX>
       <somethingElse>keep me here</somethingElse>
   </NUM>
   <URL>/out/out.ViewFolder.php</URL>
  </SomeOtherAttributeName>
</Data>

所需的输出是

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
  <PageInfo>
   <ID>0</ID>
   <URL>er.php</URL>
  </PageInfo>
  <SomeOtherAttributeName>
   <ID>1</ID>
   <NUM> 
       <somethingElse>keep me here</somethingElse>
   </NUM>
   <URL>/out/out.ViewFolder.php</URL>
  </SomeOtherAttributeName>
</Data>

1 个答案:

答案 0 :(得分:3)

使用Xml Linq。参见下面的代码

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication75
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<XElement> deleteMe = doc.Descendants().Where(x => (string)x == "DELETE ME").ToList();

            for (int i = deleteMe.Count - 1; i >= 0; i--)
            {
                deleteMe[i].Remove();
            }
        }

    }



}