Problem in XML document declaration [closed]

0

I create an XML document from code, and I need the statement to look like this:

<?xml version="1.0" encoding="UTF-8"?>

With the code that I wrote it only shows the version, How can I do it to show the coding?

<?xml version="1.0"?>

My code:

XmlDocument xmlDoc = new XmlDocument();
  XmlDeclaration xmlDeclaracion = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); ;
    
asked by Efrain Mejias C 07.02.2018 в 15:05
source

3 answers

3

here is an example

using System;
using System.IO;
using System.Xml;

public class Sample {

    public static void Main() {

    // Create and load the XML document.
    XmlDocument doc = new XmlDocument();
    string xmlString = "<book><title>Oberon's Legacy</title></book>";
    doc.Load(new StringReader(xmlString));

    // Create an XML declaration. 
    XmlDeclaration xmldecl;
    xmldecl = doc.CreateXmlDeclaration("1.0",null,null);
    **xmldecl.Encoding="UTF-8";**
    xmldecl.Standalone="yes";     

   // Add the new node to the document.
   XmlElement root = doc.DocumentElement;
   doc.InsertBefore(xmldecl, root);

   // Display the modified XML document 
  Console.WriteLine(doc.OuterXml);

  }
}

I hope your greeting is of your help

    
answered by 07.02.2018 / 15:55
source
4

The problem is probably that you are not adding the declaration to your document. You must do it with AppendChild or InsertBefore :

XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaracion = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
xmlDoc.AppendChild(xmlDeclaracion);
XmlElement root = xmlDoc.CreateElement("raiz");
xmlDoc.AppendChild(root);
xmlDoc.Save(@"c:\pruebaxml.xml");
    
answered by 07.02.2018 в 15:59
-3

So it worked perfect (I was not adding the statement I did it with the InsertBefore method):

XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDeclaracion = xmlDoc.CreateXmlDeclaration("1.0","UTF-8",null);
                XmlElement FacturaElectronica = xmlDoc.CreateElement("xs", "FacturaElectronica", UrlFacturaELectronica);
                xmlDoc.AppendChild(FacturaElectronica);
                xmlDoc.InsertBefore(xmlDeclaracion, FacturaElectronica);
    
answered by 07.02.2018 в 16:39