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

Find and delete all occurrences of a string that starts with x

我正在解析一个 XML 文件,以便将其与另一个 XML 文件进行比较。 XML Diff 工作得很好,但我们发现有很多垃圾标签存在于一个文件中,而不存在于另一个文件中,它们对我们的结果没有影响,但使报告混乱。我已经将 XML 文件加载到内存中以对它做一些其他事情,我想知道是否有一种简单的方法可以同时浏览该文件,并删除所有以开头的标签,如一个例子颜色=。颜色值满图,不好抢,全部去掉。

在XML中似乎没有任何方法可以指定,"ignore these tags"。

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

编辑:这是 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>

如果您使用 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" 子字符串是元素的 attribute,而不是元素本身。要删除所有此类属性,请使用以下方法:

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