查找并删除以 x 开头的字符串的所有匹配项

本文关键字:字符串 查找 删除 开头 | 更新日期: 2023-09-27 17:55:32

我正在解析一个XML文件,以将其与另一个XML文件进行比较。XML Diff 运行良好,但我们发现在一个文件中存在许多垃圾标记,而不是另一个文件,它们与我们的结果无关,但会使报告混乱。我已经将 XML 文件加载到内存中以对其执行其他一些操作,我想知道是否有一种简单的方法可以同时浏览该文件,并删除所有以 color= 开头的标签。颜色的值遍布地图,所以不容易抓住它们全部删除它们。

似乎没有任何方式在 XML Diff 中指定"忽略这些标记"。

我可以滚动文件,找到每个实例,找到它的结尾,将其删除,但我希望会有更简单的东西。如果没有,哦,好吧。

编辑:这是一段XML:

<numericValue color="-103" hidden="no" image="stuff.jpg" key="More stuff." needsQuestionFormatting="false" system="yes" systemEquivKey="Stuff." systemImage="yes">
    <numDef increment="1" maximum="180" minimum="30">
        <unit deprecated="no" key="BPM" system="yes" />
   </numDef>
</numericValue>

查找并删除以 x 开头的字符串的所有匹配项

如果使用 Linq to XML,则可以通过以下方式将 XML 加载到XDocument中:

        var doc = XDocument.Parse(xml); // Load the XML from a string

        var doc = XDocument.Load(fileName); // Load the XML from a file.

然后搜索具有匹配名称的所有元素,并使用System.Xml.Linq.Extensions.Remove()一次删除它们:

        string prefix = "L"; // Or whatever.
        // Use doc.Root.Descendants() instead of doc.Descendants() to avoid accidentally removing the root element.
        var elements = doc.Root.Descendants().Where(e => e.Name.LocalName.StartsWith(prefix, StringComparison.Ordinal));
        elements.Remove();

更新

在 XML 中,color="-103"子字符串是元素的属性,而不是元素本身。 若要删除所有此类属性,请使用以下方法:

    public static void RemovedNamedAttributes(XElement root, string attributeLocalNamePrefix)
    {
        if (root == null)
            throw new ArgumentNullException();
        foreach (var node in root.DescendantsAndSelf())
            node.Attributes().Where(a => a.Name.LocalName == attributeLocalNamePrefix).Remove();
    }

然后这样称呼它:

        var doc = XDocument.Parse(xml); // Load the XML
        RemovedNamedAttributes(doc.Root, "color");