Suppose there is a ready-made XML document like:

<wpt lat="59.546486655250192" lon="30.110270230099559"> <time>2017-01-21T07:12:09Z</time> <name>001</name> <sym>Flag, Blue</sym> <type>user</type> <extensions> ......... </extensions> </wpt> 

You need to insert new nodes "cmt" and "desc" exactly how

 <wpt lat="59.546486655250192" lon="30.110270230099559"> <time>2017-01-21T07:12:09Z</time> <name>001</name> <cmt>21-JAN-17 10:12:09</cmt> //это <desc>21-JAN-17 10:12:09</desc> //и это <sym>Flag, Blue</sym> <type>user</type> <extensions> ......... </extensions> </wpt> 

Insert after the tag "name" - this is sooooo fundamentally.

Is this possible using XML classes from C #? (if yes, show me pliz how) Or shines to write a prog to work with lines in the file, cut-paste ...

Thanks in advance for your valuable advice! :)

    1 answer 1

    If the documents are small or you do not have special performance requirements, then probably the easiest way is to use the XmlDocument class for high-level work with XML:

     string xmlString = ...; var doc = new XmlDocument(); doc.LoadXml(xmlString); var wptTag = doc.GetElementsByTagName("wpt").Item(0); var nameTag = doc.GetElementsByTagName("name").Item(0); var cmtTag = doc.CreateElement("cmt"); cmtTag.InnerText = "21-JAN-17 10:12:09"; wptTag.InsertBefore(cmtTag, nameTag); var descTag = doc.CreateElement("desc"); descTag.InnerText = "21-JAN-17 10:12:09"; wptTag.InsertBefore(descTag, nameTag); doc.Save("updated_file.xml"); 
    • Thank you for what you need)) - Gregory Gustavin
    • Only one question - after saving to the file you get "<cmt xmlns =" ​​"> 21-JAN-17 10:12:09 </ cmt>", how to get rid of xmlns = ""? - Gregory Gustavin
    • @GregoryGustavin hmm, strange, I'm fine. And after creating the tag, try to enter cmtTag.Attributes.RemoveAll(); ? - andreycha
    • @Ev_Hyper XmlDocument is a DOM. DOM = slow. Linq2Xml is just a linq syntax to the same DOM. And for large files it’s better to use SAX (in terms of dotnet, this is an XmlReader ). - andreycha
    • @andreycha you are right, I did not have to go to SO at one o'clock at night :) - Ev_Hyper