I have an dataset which i need to convert to xml with encoding="UTF-8 " specifiedin the xml file
SqlConnection con = new SqlConnection(dbconn);
con.Open();
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from employee", con);
DataSet ds = new DataSet();
cmd1.Fill(ds);
string strFileName = #"E:\Dif.xml";
MemoryStream memStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memStream, Encoding.UTF8);
ds.WriteXml(writer, XmlWriteMode.WriteSchema);
i see no xml file been written,
i wante dteh xml file to be written in this format in the heading
<?xml version="1.0" encoding="utf-8" ?>
so what is teh setting that i should be doing while converting dataset to xml.
please help me out, i ma using vs2003,.net 1.1 framework
thanks
prince
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter xmlWriter = XmlWriter.Create(strFileName, settings))
{
ds.WriteXml(xmlWriter);
xmlWriter.Close();
}
Use this can write xml with encoding:
<?xml version="1.0" encoding="utf-8"?>
As per Alex's suggestion, here is my comment as an answer:
Try using FileStream instead of MemoryStream: Your code should look like this:
FileStream fs =new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
ds.WriteXML(writer, XMLWriteMode.WriteSchema);
But also, please take a look at his anwer too, maybe the answer is a combination of both our answers.
I used flying19880517s answer and converted it to an extension method. To get the same result as the original WriteXml method I added Indent = true (otherwise your get the xml without newlines / spaces.
public static void WriteXml(this DataSet ds, string fileName, Encoding encoding)
{
using (var writer = XmlWriter.Create(fileName,
new XmlWriterSettings { Encoding = encoding, Indent = true, }))
ds.WriteXml(writer);
}
Have you tried XmlWriteMode.IgnoreSchema?
Taken from http://msdn.microsoft.com/en-us/library/system.data.xmlwritemode.aspx for XmlWriteMode.WriteSchema:
Writes the current contents of the
DataSet as XML data with the
relational structure as inline XSD
schema. If the DataSet has only a
schema with no data, only the inline
schema is written. If the DataSet does
not have a current schema, nothing is
written.
You are writing to a memory stream. Use a FileStream if you want output to disk.
Regards, Morten
Related
I have an XmlDocument and I am saving it with an XmlWriter, using this post. Despite setting the Encoding to Utf-8 and the file getting saved with Utf-8 encoding in fact, the xml declaration in the file has the "utf-16" as the value of the encoding attribute.
I can't see where is the error in my code:
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Encoding=Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
xDoc.Save(writer);
}
using (
StreamWriter sw = new StreamWriter(
new FileStream(strXmlName, FileMode.Create, FileAccess.Write),
Encoding.UTF8
)
)
{
sw.Write(sb.ToString());
}
The reason for this is covered in the question #dbc links to in the comments: The overload of XmlWriter.Create that accepts a StringBuilder will create a StringWriter, which has its encoding set to UTF-16.
However, in this case it's not clear why you're using a StringBuilder when your goal is to write to a file. You could create an XmlWriter for the file directly:
var settings = new XmlWriterSettings
{
Indent = true
};
using (var writer = XmlWriter.Create(strXmlName, settings))
{
xDoc.WriteTo(writer);
}
The encoding here will default to UTF-8.
As an aside, I'd suggest you check out the much newer XDocument and friends, it's a much more friendly API than XmlDocument.
This problem is most likely pretty simple, but I am making a dataset and trying to save it to a file using XMLTextWriter
Now when i save my dataset and then attempt to read it will read the table names but shows the rows as 0? So it seems my writer is not writing the rows of the table?
Anyone know how I can fix this?
public static DataSet liveData = new DataSet();
public static DataTable players = new DataTable("Players");
public static void WriteSchemaWithXmlTextWriter()
{
// Set the file path and name. Modify this for your purposes.
string filename = "Schema.xml";
// Create a FileStream object with the file path and name.
System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
// Create a new XmlTextWriter object with the FileStream.
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Unicode);
// Write the schema into the DataSet and close the reader.
liveData.WriteXmlSchema(writer);
writer.Close();
}
public static void ReadSchemaFromXmlTextReader()
{
// Set the file path and name. Modify this for your purposes.
string filename = "Schema.xml";
// Create a FileStream object with the file path and name.
System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
// Create a new XmlTextReader object with the FileStream.
System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stream);
// Read the schema into the DataSet and close the reader.
liveData.ReadXmlSchema(xmlReader);
Console.WriteLine("y: {0}", liveData.Tables["Players"].Rows.Count);
xmlReader.Close();
}
Thank you for your help in advance :)
You are writing the schema, which is the layout/structure of the Xml, rather than the actual content.
You need to use DataSet.WriteXml ...
https://msdn.microsoft.com/en-us/library/ms135426%28v=vs.110%29.aspx
... instead!
I have a problem when I deserialize the xml into List of Objects. I searched it on the net this morning, but my problem isn't resolved.
Deserialization method
public static List<FileAction> DeSerialization()
{
XmlRootAttribute xRoot=new XmlRootAttribute();
xRoot.ElementName="ArrayOfSerializeClass";
xRoot.IsNullable=true;
XmlSerializer serializer = new XmlSerializer(typeof(List<FileAction>),xRoot);//, new XmlRootAttribute("ArrayOfSerializeClass")
using (Stream streamReader = File.OpenRead(#"C:\serialization\SerializationWithFileWatcher\Output\XmlSerialize.xml"))//FileStream fs =new FileStream(xmlPath,FileMode.Open)
{
using (XmlReader reader = XmlReader.Create(streamReader))
{
int count =0;
List<FileAction> serialList2 = (List<FileAction>)serializer.Deserialize(reader);
return (List<FileAction>)serializer.Deserialize(reader);
}
}
Calling Method
String resultPath = #"C:\serialization\SerializationWithFileWatcher\Output\XmlSerialize.xml";
if (!File.Exists(resultPath))
{
XmlSerializer xs = new XmlSerializer(typeof(List<SerializeClass>));
using (FileStream fileStream = new FileStream(#"C:\serialization\SerializationWithFileWatcher\Output\XmlSerialize.xml", FileMode.Create))
{
xs.Serialize(fileStream, serializeList);//seri
fileStream.Close();
}
Console.WriteLine("Succesfully serialized to XML");
}
else
{
//string path= #"C:\serialization\SerializationWithFileWatcher\Output\XmlSerialize.xml";
DeSerialization();
XmlSerializer xs = new XmlSerializer(typeof(List<SerializeClass>));
FileStream fs = new FileStream(#"C:\serialization\SerializationWithFileWatcher\Output\XmlSerialize.xml", FileMode.Append, FileAccess.Write);
using (XmlWriter xwr = XmlWriter.Create(fs))//TextWriter xwr = new StreamWriter
{
xs.Serialize(xwr, serializeList);//seri
//fs.Close();
}
Console.WriteLine("Succesfully serialized to XML");
}
return serializeList;
The reason why I am calling it here is that I want to add this object again to the xml file.
THe error is that here is an error in XML document (15,27).
My Xml structure
<?xml version="1.0"?>
<ArrayOfSerializeClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SerializeClass>
<creationTime>2013-11-25T09:53:25.3325289+05:30</creationTime>
<fileAction>Renamed</fileAction>
<Properties>
<FileAttributes fileName="validate json.txt">
<fileSize>307</fileSize>
<extension>.txt</extension>
<lastAccessTime>2013-11-25T09:53:25.3325289+05:30</lastAccessTime
<fullPath>C:\serialization\SerializationWithFileWatcher\SerializationWithFileWatcherProj\validate json.txt</fullPath>
</FileAttributes>
</Properties>
</SerializeClass>
</ArrayOfSerializeClass>
What I understand from the code above is that you are trying to extend the current XML, by first reading it as a FileStream and then using an XmlWriter to add some more content to it.
If my understanding is correct, then you are trying to write to the end of an existing XML file, which is not allowed since any XML document can have only one root node. In your case, that root node is ArrayOfSerializeClass.
So, in order to successfully achieve your task, you must append your XML within the root node.
Update:
Possible solution here: how to append a xml file in c#?
I am trying to apply a XSL style sheet on a source xml and write the output to a target xml file. The xsl removes the xml comments present inside the source xml.
The target xml file has UTF-16 encoding in the header.
But still i want the output xml to be utf-8 encoding. The code i used is
XmlWriterSettings xwrSettings = new XmlWriterSettings();
**xwrSettings.Encoding = Encoding.UTF8;**
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("sample.xsl");
StringBuilder sb = new StringBuilder();
XmlReader xReader = XmlReader.Create("Source.xml");
XmlWriter xWriter = XmlWriter.Create(sb, xwrSettings);
xslt.Transform(xReader, xWriter);
File.WriteAllText("Target.xml",sb.ToString());
I tried to set the xml writer setting to be of UTF-8 but it is not working.
Since you are writing to file, why not just use:
using (XmlReader xReader = XmlReader.Create("Source.xml"))
using (XmlWriter xWriter = XmlWriter.Create("Target.xml", xwrSettings)) {
xslt.Transform(xReader, xWriter);
}
// your file is now written
What is the best way to create xml file in .net 2.0 in terms of nodes etc. I dont think I could use LINQ. Any code sample or article would be helpful.
You best bet is to use the XmlTextWriter class.
Here's a pretty basic example:
var writer = new XmlTextWriter("Foo.xml", Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("Foo");
writer.WriteAttributeString("hello", "world");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
This will give you:
<?xml version="1.0" encoding="utf-8"?>
<Foo hello="world" />
Here's a code snippet that works:
XmlTextWriter myXW = new XmlTextWriter(#"C:\NewXmlFile.xml", Encoding.UTF8)
myXW.WriteStartDocument();
myXW.WriteStartElement("Customers");
string strConn = myConnectionString;
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbCommand myCMD = new OleDbCommand("select * from customers", myConn);
OleDbDataReader myRdr = myCMD.ExecuteReader();
while (myRdr.Read())
{
myXW.WriteStartElement("Customer");
myXW.WriteAttributeString("id", myRdr.GetString(0));
myXW.WriteElementString("companyname", myRdr.GetString(1));
myXW.WriteElementString("contactname", myRdr.GetString(2));
myXW.WriteElementString("contactname", myRdr.GetString(3));
myXW.WriteElementString("address", myRdr.GetString(4));
myXW.WriteElementString("city", myRdr.GetString(5));
myXW.WriteElementString("country", myRdr.GetString(8));
myXW.WriteElementString("phone", myRdr.GetString(9));
myXW.WriteElementString("fax", myRdr.GetString(10));
myXW.WriteEndElement();
}
myXW.WriteEndElement();
myXW.WriteEndDocument();
myXW.Flush();
myXW.Close();