Flat xml file c# - c#

I'm wrting xml file with UTF-8 (without Bom) encoding as follow:
xmldecl.Encoding = "UTF-8";
dataDoc.InsertBefore(xmldecl, root);//dataDoc is XmlDocument object
using (var writer = new XmlTextWriter(targetPath, new UTF8Encoding(false)))
{
dataDoc.Save(writer);
}
My "problem" is the file is saved in one line instead of xml formatting,
I.e if i have the following xml:
<ElementA>
<ElementB/>
</ElementA>
With my code the xml file will be:
<ElementA><ElementB/></ElementA>
Instead of xml format.
How can i solve it?
*I'm try to open the file with Notepad++
Thanks.

XmlTextWriter has a property Formatting to define the way the output is written:
using (var writer = new XmlTextWriter(targetPath, new UTF8Encoding(false)))
{
writer.Formatting = Formatting.Indented;
dataDoc.Save(writer);
}

Related

How can I save an XmlDocument without the XML Prolog?

While working on csproj files as xml files (xmlDocument) somehow after saving, encoding changes from UTF-8 to ASCII. The only solution I figured out is to use StreamWriter with declared encoding. But this adds a header to file.
Questions:
1. Do you know any other solution to this problem?
2. Can I leave changed csproj?
StreamReader sr = new StreamReader(projectFilePath, Encoding.UTF8);
XmlDocument xmlCsproj = new XmlDocument();
xmlCsproj.Load(sr);
sr.Close();
// Working on XML nodes (replace references paths)
StreamWriter sw= new StreamWriter(projectFilePath, false, Encoding.UTF8);
xmlCsproj.Save(sw);
sw.Close();
This should work?
var writer = new XmlTextWriter(projectFilePath, Encoding.UTF8)
{
Formatting = Formatting.Indented
};
xmlCsproj.WriteContentTo(writer);
writer.Close();
First of all, UTF8 character values are identical to US-ASCII values in the range 0-127. There's no way to say if a csproj file was saved as US-ASCII or UTF8 unless the file contained non-English text, like non-English file paths. Is that what happened here? Even so, XmlDocument.Save should have used UTF8 by default.
You can control how an XmlDocument is written to a stream or file using an XmlWriter and XmlWriterSettings. In this case, you need to set the OmitXmlDeclaration :
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
var writer = XmlWriter.Create(projectFilePath, settings);
xmlCsproj.Save(sw);
sw.Close();
The default encoding is UTF8. To change it, you can set the XmlWriterSettings.Encoding to a different value

XDocument automatically indents files on parse and does not remove indent on save

I am seeking a help regarding file saving of XML file using XDocument (NOT XMLDocument).
So I have a xml file that does not have indentation (in fact it is 1 line). When I read this to XDocument using XDocument.Parse (after reading and storing string using StreamReader), the resulting XDocument is indented.
Alright, I thought it will be fine as long as if I can save it back to the file without indentation. However, even though I have
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.NewLineOnAttributes = false;
writerSettings.NewLineHandling = NewLineHandling.None;
writerSettings.Indent = false;
and pass that in when I create XmlWriter
using (var writer = XmlWriter.Create(u.ToFileSystemPath(), settings))
{
xd.Save(writer);
}
The resulting XML file still has indentation. When I am debugging on Visual studio, I noticed that the writer is a class XmlWellFormedWriter. Does this have something to do with my result? Any help would be appreciated.
Thank you.
SaveOptions are available on Save() as well as ToString().
string xmlstring =
#"<Top>
<First>1</First>
<Second>Dude</Second>
<Third>Now</Third>
</Top>";
XDocument doc = XDocument.Parse(xmlstring);
doc.Save(#"C:\temp\noIndet.xml", SaveOptions.DisableFormatting);
// string noIndent = doc.ToString(SaveOptions.DisableFormatting);
Output:

How to pass and get the string based xml data in xslt transform using C#?

I want to convert one xml file into another xml file using xslt.here, i can able to pass the input document to the XPathDocument and also save the output file in disk by passing outfile into XmlTextWriter.
But now my problem is... i have my input is in string format and i also want output as a string.Instead of passing the location of the input file, i want to pass string that contains the xml data.
so i have to pass string object into xpathDoccument in someway and also get the resultant xml file as a string.Instead of save the output as a file,i want output as a string.
XPathDocument xpathDoc = new XPathDocument("C:\\InputXml.xml");
XslCompiledTransform xslt = new XslCompiledTransform();
string xsltFile = "C:\\conversion.xslt";
xslt.Load(xsltFile);
string outputFile = "C:\\myHtml.html";
XmlTextWriter writer = new XmlTextWriter(outputFile, null);
xslt.Transform(xpathDoc, null, writer);
writer.Close();
Please guide me to get out of this issue...
XPathDocument accepts TextReader. You can give a stream as new XPathDocument(new StringReader(xmlstring)). Similarly XmlTextWriter accepts TextWriter. So you can pass a StringWriter.
--edit--
var sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
xslt.Transform(xpathDoc, null, writer);
var str= sw.ToString();
Try this,
XslTransform xTrans = new XslTransform();
xTrans.Load(nodeXsltPath); //xsl file path
XmlDocument input= new XmlDocument();
XmlDocument output= new XmlDocument();
input.LoadXml(xmlString); /* Xml string to be loaaded */
output.Load(xTrans.Transform(input,null,new XmlUrlResolver()));
output.Save(filePathtoSave);

Deserialization error in XML document(1,1)

I have an XML file that I deserialize, the funny part is the XML file is the was serialized
using the following code:
enter code here
var serializer = new XmlSerializer(typeof(CommonMessage));
var writer = new StreamWriter("OutPut.txt");
serializer.Serialize(writer, commonMessage);
writer.Close();
And i m trying to deserialized it again to check if the output match the input.
anyhow here is my code to deserialize:
var serializer = new XmlSerializer(typeof(CommonMessage));
var reader = new StringReader(InputFileName);
CommonMessage commonMessage = (CommonMessage)serializer.Deserialize(reader);
Replace StringReader with StreamReader and it will work fine. StringReader reads value from the string (which is file name in your case).
I just had the same error message but different error source. In case someone has the same problem like me. I chopped off the very first char of my xml string by splitting strings. And the xml string got corrupted:
"?xml version="1.0" encoding="utf-16"?> ..." // my error
"<?xml version="1.0" encoding="utf-16"?> ..." // correct
(1,1) means basically first char of the first line is incorrect and the string can't be deserialized.
include in your CommonMessage class the XmlRoot element tag with your xmlroot eg:[XmlRoot("UIIVerificationResponse")]
You should disable the order mark in the StreamWriter constructor like this:
UTF8Encoding(false)
Full sample:
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
xmlSerializer.Serialize(writer, objectToSerialize, ns);
return Encoding.UTF8.GetString(stream.ToArray());
}

Lost XML file declaration using DataSet.WriteXml(Stream)

I had a Dataset with some data in it. When I tried to write this DataSet into a file, everything was OK. But When I tried to write it into a MemoryStream, the XML file declaration was lost.
The code looks like:
DataSet dSet = new DataSet();
//load schema, fill data in
dSet.WriteXML("testFile.xml");
MemoryStream stream = new MemoryStream();
dSet.WriteXML(stream);
stream.Seek(0,SeekOrigin.Begin);
When I opened file testFile.xml, I got:
<?xml version="1.0" standalone="yes"?>
//balabala
But When I open the stream with StreamReader, I only got:
//balabala
Somebody said I can insert XML file declaration in my stream manually. It works but seems so ugly. Do you know why it dropped the first line and any more simple solution?
It wasn't dropped. Simply not included. Though it is highly recommend the xml declaration is not a required element of the xml specification.
http://msdn.microsoft.com/en-us/library/ms256048(VS.85).aspx
You can use XmlWriter.WriteStartDocument to include the xml declaration in the stream like so:
MemoryStream stream = new MemoryStream();
var writer = XmlWriter.Create(stream);
writer.WriteStartDocument(true);
dSet.WriteXML(stream);
I try your solution with DataTable and don't work correctly.
using (MemoryStream stream = new MemoryStream()) {
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) {
writer.WriteStartDocument(); //<?xml version="1.0" encoding="utf-8"?>
writer.WriteRaw("\r\n"); //endline
writer.Flush(); //Write immediately the stream
dTable.WriteXml(stream);
}
}
If you disassemble the 2.0 code you'll see that the WriteXml method that takes a file name explictly writes out the declaration (XmlWriter.WriteStartDocument) but the WriteXml methods that take a stream or writer do not.

Categories

Resources