【问题标题】:Inserting new elements in the end of an svg file在 svg 文件的末尾插入新元素
【发布时间】:2022-07-22 16:19:02
【问题描述】:

我有一个 svg 文件,我想使用 c# 和 XPath 在其中插入一个圆圈:

这是之前的文件内容:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="594.75pt" height="841.5pt" viewBox="0 0 594.75 841.5" style="border: 1px solid red">
<circle cx="50%" cy="50%" r="50" fill="red" />
</svg>

我想要这个文件内容之后:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="594.75pt" height="841.5pt" viewBox="0 0 594.75 841.5" style="border: 1px solid red">
<circle cx="50%" cy="50%" r="50" fill="red" />
<circle stroke="blue" stroke-width="3" cx="148.63pt" cy="401.02pt" r="84.15" fill-opacity="0.1"/> 
</svg>

我正在使用以下代码:

XmlDocument doc = new XmlDocument();
doc.Load(@"D:\\test.svg");

XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
xmlnsManager.AddNamespace("svg", "http://www.w3.org/2000/svg");

XmlDocumentFragment xmlDocFrag = doc.CreateDocumentFragment();
xmlDocFrag.InnerXml = @"<circle stroke=\"blue\" stroke-width=\"3\" cx=\"148.63pt\" cy=\"401.02pt\" r=\"84.15\" fill-opacity=\"0.1\"/>";

XmlElement mapElement = (XmlElement)doc.SelectSingleNode(@"//svg[last()]", xmlnsManager);
mapElement.AppendChild(xmlDocFrag);  // <----- null !!

doc.Save(path);

但是,在 SelectSingleNode 之后 mapElement 为 null :( 我希望它是现有的圆形元素。

【问题讨论】:

    标签: c# xml svg xpath


    【解决方案1】:

    您获得null 的原因是因为您没有将xmlnsManager 中定义的命名空间别名添加到您的XPath。

    XmlElement mapElement = (XmlElement)doc.SelectSingleNode(@"//svg:svg[last()]", xmlnsManager);
    

    或者更简单

    XmlElement mapElement = (XmlElement)doc.SelectSingleNode(@"/svg:svg", xmlnsManager);
    

    你甚至根本不需要 XPath

    XmlElement mapElement = (XmlElement)doc["svg"];
    

    dotnetfiddle


    使用较新的 XDocumentXElement 类似乎更容易

    var xDoc = XDocument.Load(path);
    var xmlns = xDoc.Root.GetDefaultNamespace();
    xDoc.Root.Add(new XElement(xmlns + "circle",
                            new XAttribute("stroke","blue"),
                            new XAttribute("stroke-width","3"),
                            new XAttribute("cx","148.63pt"),
                            new XAttribute("cy","401.02pt"),
                            new XAttribute("r","84.15"),
                            new XAttribute("fill-opacity","0.1")
                              )
                 );
    
    xDoc.Save(path);
    

    dotnetfiddle

    【讨论】:

    • 我同意,但这确实回答了我的问题
    • 已添加说明您现有代码无法正常工作的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 2019-11-30
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多