用 href 链接替换 SVG 内部文本值

问题描述 投票:0回答:1
c# xml linq svg linq-to-xml
1个回答
0
投票

以下使用 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);
            }
            //doc.Save(filename);
        }

    }

}
© www.soinside.com 2019 - 2024. All rights reserved.