使用 XElement 删除 XML 中的多个属性
Removing Multiple Attributes in XML using XElement
这是我的 xml(或者说 svg):
<svg xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
inkscape:version="0.48.2 r9819"
sodipodi:docname="android.svg" viewbox="0 0 32 54">
[Some nodes below]
</svg>
从这个中,我想删除名称包含 inkscape
或 sodipodi
的所有属性(在这种情况下,应该保留的属性是 viewbox
。
希望你能在这方面帮助我。谢谢!
这是一种可能的方式:
var raw = @"<svg xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd'
xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape'
inkscape:version='0.48.2 r9819'
sodipodi:docname='android.svg' viewbox='0 0 32 54'>
[Some nodes below]
</svg>";
var svg = XElement.Parse(raw);
var keywords = new[] { "inkscape", "sodipodi" };
svg.Attributes()
.Where(o => keywords.Any(k => o.Name.ToString().Contains(k)))
.Remove();
Console.WriteLine(svg.ToString());
输出:
<svg viewbox="0 0 32 54">
[Some nodes below]
</svg>
这是我的 xml(或者说 svg):
<svg xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
inkscape:version="0.48.2 r9819"
sodipodi:docname="android.svg" viewbox="0 0 32 54">
[Some nodes below]
</svg>
从这个中,我想删除名称包含 inkscape
或 sodipodi
的所有属性(在这种情况下,应该保留的属性是 viewbox
。
希望你能在这方面帮助我。谢谢!
这是一种可能的方式:
var raw = @"<svg xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd'
xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape'
inkscape:version='0.48.2 r9819'
sodipodi:docname='android.svg' viewbox='0 0 32 54'>
[Some nodes below]
</svg>";
var svg = XElement.Parse(raw);
var keywords = new[] { "inkscape", "sodipodi" };
svg.Attributes()
.Where(o => keywords.Any(k => o.Name.ToString().Contains(k)))
.Remove();
Console.WriteLine(svg.ToString());
输出:
<svg viewbox="0 0 32 54">
[Some nodes below]
</svg>