更改在 c# 中存储 xml 的字符串变量


string content = ....

我有一些XML内容存储在一个字符串中,如上面的变量所示。存储的内容类似于下面,

<?xml version="1.0"?>
<model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<ItemModel xsi:type="TypeKeep">
<Name>Name01</Name>
</ItemModel>
<ItemModel xsi:type="TypeDelete">
<Name>Name02</Name>
</ItemModel>
<ItemModel xsi:type="TypeDelete">
<Name>Name03</Name>
</ItemModel>
</Items>
</model>

在这里,我想删除所有具有 type="TypeDelete" 的元素。从某种意义上说,我试图通过删除TypeDelete的精灵来更改内容变量

知道我如何实现这一目标吗?

Using xml linq :

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

namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:temptest.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XDocument doc = XDocument.Parse(xml);
XNamespace xsiNs = doc.Root.GetNamespaceOfPrefix("xsi");
List<XElement> removeNodes = doc.Descendants("ItemModel").Where(x => (string)x.Attribute(xsiNs + "type") == "TypeDelete").ToList();
for (int i = removeNodes.Count - 1; i >= 0; i--)
{
removeNodes[i].Remove();
}
}
}
}

如果要直接从 XML 文件中删除特定的 XML 节点,可以通过此链接并尝试此操作

最新更新