提问人:chriswaddle 提问时间:10/19/2023 更新时间:10/19/2023 访问量:52
将 SVG innertext 值替换为 href 链接
Replace SVG innertext value with a href link
问:
我正在使用与XML相同的SVG文件。 我需要将某些元素的 InnerText 替换为带有 InnerText 的 href 新元素
我的元素的一个例子是
<text xmlns="http://www.w3.org/2000/svg" xml:space="preserve" fill="#ff0000" stroke-width="0" x="239.61" y="74.89" font-size="3.37" opacity="1.00" font-family="Arial Narrow">3070119100</text>
我需要将 3070119100 InnerText 替换为
<a link:href="http://www.google.it">3070119100</a>
我想我需要添加一个具有 InnerText 的子值。
我想使用 LINQ XDocument,但也喜欢使用 XMLDocument 编写代码。
我能做什么: 我能够使用XMLDocument添加子元素,但不能清除innerText文本元素:
XmlDocument doc = new XmlDocument();
doc.Load(_SVG);
XmlNodeList elementListText = doc.GetElementsByTagName("text");
for (int i = 0; i < elementListText.Count; i++)
{
XmlElement a = doc.CreateElement("a");
a.SetAttribute("xmlns", "http://www.w3.org/2000/svg");
a.SetAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
a.SetAttribute("xlink:href", "http://www.google.it");
a.InnerText = elementListText[i].InnerText;
elementListText[i].AppendChild(a);
}
doc.Save(_SVG_TEXT);
通过这种方式,我得到了两次值,一个未链接(上一个)和一个链接(href 值),但我无法清除文本 InnerText。
谢谢!
答:
1赞
jdweng
10/19/2023
#1
以下使用 Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApp10
{
class Program
{
static void Main(string[] args)
{
string _SVG = @"<text xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/2000/svg"" xml:space=""preserve"" fill=""#ff0000"" stroke-width=""0"" x=""239.61"" y=""74.89"" font-size=""3.37"" opacity=""1.00"" font-family=""Arial Narrow"">3070119100</text>";
XDocument doc = XDocument.Parse(_SVG);
//to read from file
//XDocument doc = XDocument.Load(filename);
XNamespace ns = doc.Root.GetDefaultNamespace();
XNamespace xlink = doc.Root.GetNamespaceOfPrefix("xlink");
List<XElement> elementListText = doc.Descendants(ns + "text").ToList();
foreach(XElement element in elementListText)
{
string value = element.Value;
element.RemoveNodes();
XElement a = new XElement(ns + "a");
a.SetAttributeValue(ns + "xlink", "http://www.w3.org/1999/xlink");
a.SetAttributeValue(xlink + "href", "http://www.google.it");
a.SetValue(value);
element.Add(a);
}
//doc.Save(filename);
}
}
}
评论