我正在解析一个 XML 文件,以便将它与另一个 XML 文件进行比较。 XML Diff 工作得很好,但我们发现有很多垃圾标签存在于一个文件中,而不存在于另一个文件中,它们对我们的结果没有影响,但使报告变得困惑。我已经将 XML 文件加载到内存中以对它做一些其他事情,我想知道是否有一种简单的方法可以同时浏览该文件,并删除所有以 color= 开头的标签.颜色的值遍布整个 map ,因此不容易捕获它们并将它们全部删除。
在 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>
最佳答案
如果您使用 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");
关于c# - 查找并删除所有以 x 开头的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30768743/