How to Print <Xml Version="1.0"> Using Xdocument

How to print ?xml version=1.0? using XDocument

By using XDeclaration. This will add the declaration.

But with ToString() you will not get the desired output.

You need to use XDocument.Save() with one of his methods.

Full sample:

var doc = new XDocument(
new XDeclaration("1.0", "utf-16", "yes"),
new XElement("blah", "blih"));

var wr = new StringWriter();
doc.Save(wr);
Console.Write(wr.ToString());

Xdocument does not print declaration

How are you printing out the contents of your XDocument?

The .ToString() method does not include the xml header, but the .Save() method does.

Edit: The same answer was given here.

XDocument.ToString() drops XML Encoding Tag

Either explicitly write out the declaration, or use a StringWriter and call Save():

using System;
using System.IO;
using System.Text;
using System.Xml.Linq;

class Test
{
static void Main()
{
string xml = @"<?xml version='1.0' encoding='utf-8'?>
<Cooperations>
<Cooperation />
</Cooperations>";

XDocument doc = XDocument.Parse(xml);
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
Console.WriteLine(builder);
}
}

You could easily add that as an extension method:

public static string ToStringWithDeclaration(this XDocument doc)
{
if (doc == null)
{
throw new ArgumentNullException("doc");
}
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
return builder.ToString();
}

This has the advantage that it won't go bang if there isn't a declaration :)

Then you can use:

string x = doc.ToStringWithDeclaration();

Note that that will use utf-16 as the encoding, because that's the implicit encoding in StringWriter. You can influence that yourself though by creating a subclass of StringWriter, e.g. to always use UTF-8.

How to prevent XDocument from adding XML version and encoding information

That's the behaviour of the XDocument.Save method when serializing to a file or a TextWriter. If you want to omit the XML declaration, you can either use XmlWriter (as shown below) or call ToString. Refer to Serializing with an XML Declaration.

XDocument xmlDoc = XDocument.Load(FileManager.SourceFile); 

// perform your modifications on xmlDoc here

XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter xw = XmlWriter.Create(targetFile, xws))
xmlDoc.Save(xw);

xml.LoadData - Data at the root level is invalid. Line 1, position 1

The hidden character is probably BOM.
The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object.
On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.

How to use XDocument to update existing xml file which has namespace requirements?

Try following :

            XDocument xml = XDocument.Load(_xmlFilePath);
XElement root = xml.Root;
XNamespace ns = root.GetDefaultNamespace();

root.Add(new XElement(ns + "Event",

Force XDocument to write to String with UTF-8 encoding

Try this:

using System;
using System.IO;
using System.Text;
using System.Xml.Linq;

class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml",
LoadOptions.PreserveWhitespace);
doc.Declaration = new XDeclaration("1.0", "utf-8", null);
StringWriter writer = new Utf8StringWriter();
doc.Save(writer, SaveOptions.None);
Console.WriteLine(writer);
}

private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
}

Of course, you haven't shown us how you're building the document, which makes it hard to test... I've just tried with a hand-constructed XDocument and that contains the relevant whitespace too.

XDocument.Load losing Declaration

I suspect it's not really dropping the declaration on load - it's when you're writing the document out that you're missing it. Here's a sample app which works for me:

using System;
using System.Xml.Linq;

class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml");
Console.WriteLine(doc.Declaration);
}
}

And test.xml:

<?xml version="1.0" encoding="us-ascii" ?>
<Foo>
<Bar />
</Foo>

Output:

<?xml version="1.0" encoding="us-ascii"?>

The declaration isn't shown by XDocument.ToString(), and may be replaced when you use XDocument.Save because you may be using something like a TextWriter which already knows which encoding it's using. If you save to a stream or just to a filename, it's preserved in my experience.



Related Topics



Leave a reply



Submit