我有一个结构如下的文档,并且我试图删除所有出现的“ 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>
答案 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();
}
}
}
}