1

I am Trying to export xml from some data in C#

XDocument doc = XDocument.Parse(xml);

After I save the XML, I found that the XML contains

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

Which i did not enter at all, and cause problem like following.

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="..\..\dco.xsl"?>
<S>
  <B>
  </B>
</S>

I dont want the first row to appear, any ideas? Thanks for your respond.

Jeffrey Chan
  • 93
  • 1
  • 5
  • 11

3 Answers3

2

If I understood correctly, you need an XML file without the header. Take a look at this answer.

Basically, you will need to initialize XmlWriter and XmlWriterSettings classes and then call doc.Save(writer).

Community
  • 1
  • 1
Miroslav Popovic
  • 12,100
  • 2
  • 35
  • 47
2

Its PI (processing instruction) its required and contained important information which is used while processing xml file.

Try this while writing xml file:

XmlWriter w;
w.Settings = new XmlWriterSettings();
w.Settings.ConformanceLevel = ConformanceLevel.Fragment;
w.Settings.OmitXmlDeclaration = true;

Omitting XML processing instruction when serializing an object

Removing version from xml file

http://en.wikipedia.org/wiki/Processing_Instruction

Community
  • 1
  • 1
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178
2

What you are saying is "AFTER" you parse with the string as you see above your result contains duplicate declarations?

Now i am not sure how you are saving your response but here is a sample application which produces similar results.

XDocument doc = XDocument.Parse("<?xml-stylesheet type=\"text/xsl\" href=\"dco.xsl\"?><S><B></B></S>");
            doc.Save(Console.OpenStandardOutput());

Produces the result:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dco.xsl"?>
<S>
  <B></B>
</S>

Which is the problem you have. You need to remove the xml declaration before saving. This can be done by using an xml writer when saving your xml output. Here is the sample application with an extension method to write the new document without the declaration.

class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse("<?xml-stylesheet type=\"text/xsl\" href=\"dco.xsl\"?><S><B></B></S>");
            doc.SaveWithoutDeclaration(Console.OpenStandardOutput());
            Console.ReadKey();
        }


    }

    internal static class Extensions
    {
        public static void SaveWithoutDeclaration(this XDocument doc, string FileName)
        {
            using(var fs = new StreamWriter(FileName))
            {
                fs.Write(doc.ToString());
            }
        }

        public static void SaveWithoutDeclaration(this XDocument doc, Stream Stream)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(doc.ToString());
            Stream.Write(bytes, 0, bytes.Length);
        }
    }
Nico
  • 12,493
  • 5
  • 42
  • 62