Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to shorten the XDeclaration of an XDocument?

I'm adding an XDeclaration to my Xdocument as follows:

XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes")

This gives me the result:

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

I'm building XML for Quickbooks Merchant Services so I only need:

<?xml version="1.0"?>

Is it possible to do this?

like image 594
David Avatar asked Jan 31 '26 15:01

David


2 Answers

You can try using custom StringWriter which doesn't provide any encoding, for example :

public class StringWriterNoEncoding : StringWriter
{
    public override Encoding Encoding
    {
        get { return null; }
    }
}

Then use StringWriterNoEncoding to print the XML :

XDocument xdoc = new XDocument(new XDeclaration("1.0", "", ""), new XElement("Root"));
var sw = new StringWriterNoEncoding();
xdoc.Save(sw);
Console.WriteLine(sw.ToString());
//above will print :
//<?xml version="1.0"?>
//<Root />
like image 135
har07 Avatar answered Feb 02 '26 03:02

har07


Set encoding and standalone to null:

XDocument xml = new XDocument(new XDeclaration("1.0", null, null)

will give

<?xml version="1.0"?>
like image 44
Frank Avatar answered Feb 02 '26 05:02

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!