我想用 C# 正则表达式
通过他的类名提取一个 svg 元素
。
例如我有这个:
<path fill="none" ... class="highcharts-tracker highcharts-tracker" ... stroke-width="22" zIndex="2" style=""/>
我想删除所有以 highcharts-tracker
作为类名的路径元素:
new Regex("");
有人知道吗?
最佳答案
在 LINQ to XML 中,这非常简单:
var classToRemove = "highlights-tracker";
var xml = XDocument.Parse(svg);
var elements = doc.Descendants("path")
.Where(x => x.Attribute("class") != null &&
x.Attribute("class")
.Value.Split(' ')
.Contains(classToRemove));
// Remove all the elements which match the query
elements.Remove();
您应该不使用正则表达式来尝试解析 XML...现有 API 可以很好地处理 XML,而正则表达式不是合适的工具。
编辑:如果格式不正确(您应该从一开始就说),您应该尝试弄清楚为什么它格式不正确并在尝试执行任何操作之前修复它其他处理。如今,XML 格式错误真的没有任何借口……几乎所有现有平台都有大量优秀的 XML API。
关于c# - 使用正则表达式按类名选择 xml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16396017/