-1

I have a xml file which I want to open and write in. The xml file has this structure:

 <?xml version="1.0" encoding="UTF-8"?>        
   <polygons>               
     <polygon name="polygon-1">        
         <point>    
            <x>38,241885</x>    
            <y>-5,965407</y>    
         </point>    
          <point>        
            <x>38,242251</x>        
            <y>-5,965423</y>        
         </point>        
    </polygon>
    <polygon name="polygon-2">
        .
        .
    </polygon>
  </polygons>   

I want to add new polygons into my xml, so I have to read it and then add a polygon at the last position. ¿How can I do this?

dbz
  • 411
  • 7
  • 22

2 Answers2

1

Here are a few different methods using xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication59
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><polygons></polygons>";

            XDocument doc = XDocument.Parse(xmlHeader);
            XElement polygons = doc.Root;

            polygons.Add(new XElement("polygon", new object[] {
                new XAttribute("name","polygon-1"),
                new XElement("point", new object[] {
                    new XElement("x","38,241885"),
                    new XElement("y","5,965407")
                })
            }));

            XElement polygon = polygons.Element("polygon");

            XElement newPoint = new XElement("point", new object[] {
                    new XElement("x","38,241885"),
                    new XElement("y","5,965407")
                });

            polygon.Add(newPoint);

        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • and where do you load the xml file? @jdweng – dbz Jun 07 '17 at 14:57
  • This code works, its the same as @jdweng code but I've included some code lines to load and save xml file `XDocument doc = XDocument.Load(@"data/polygons.xml");` and `doc.Save(@"data/polygons.xml");` – dbz Jun 07 '17 at 15:34
  • You can either use Load(Filename or URI), or use Parse(string). I used a string with Parse in my example. Simply change Parse to Load to read from a file. – jdweng Jun 07 '17 at 16:11
0

you can generate C#(polygon/point/etc) code using xsd.exe by xml file(step by step instruction: https://msdn.microsoft.com/en-us/library/5s2x1sy7(v=vs.110).aspx).

add objects to list of poligons and serialize structure using XmlSerializer https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx

kain64b
  • 2,258
  • 2
  • 15
  • 27