0

I'm trying to add some "rect" elements to svg document through c# console app. An "rect" elements are adding and they are present in structure of svg document, but they are invisible.

When i added "rect" element manually then everything was okay.

Svg image after app execution app result

Svg after adding "rect" manually manual result

There is my code

    public static MemoryStream Draw(Stream stream)

    {
        var outputStream = new MemoryStream();

        var svgDocument = XDocument.Load(stream);

        if (svgDocument.Root != null)
        {
            var gElements = svgDocument.Root.Elements("{http://www.w3.org/2000/svg}g");

            var damageLayer = gElements.FirstOrDefault(x => x.Attribute("id")?.Value == "Damages");

            var damage = new XElement("rect", new XAttribute("x", 205), new XAttribute("y", 205), new XAttribute("width", 15), new XAttribute("height", 15));

            damageLayer.Add(damage);
        }

        svgDocument.Save(outputStream);

        return outputStream;
    }

Do you have any suggestions or ways to solve that problem? If you do, please, let me know. Any help appreciates

  • Possible duplicate of [C# - How to remove xmlns from XElement](https://stackoverflow.com/questions/40517306/c-sharp-how-to-remove-xmlns-from-xelement) – X39 May 14 '19 at 12:25
  • Are you sure that this problem is caused by "xmlns" attribute? – Oleksa Kachmarskyi May 14 '19 at 12:28
  • You change the default namespace to nothing https://www.w3schools.com/xml/xml_namespaces.asp `Default Namespace` The alternative would be to provide the proper svg namespace in your rect – X39 May 14 '19 at 12:35
  • I removed "xmlns" attribute, but nothing changed – Oleksa Kachmarskyi May 14 '19 at 13:02

1 Answers1

1

You need to create the rect in the SVG namespace i.e.

XNamespace namespace = "http://www.w3.org/2000/svg";
var damage = new XElement(namespace + "rect", ...
Robert Longson
  • 118,664
  • 26
  • 252
  • 242