C# Diffgram to XElement, Reader/Writer confusion - c#

How do I obtain the Diffgram of a DataSet in an XElement? (Or XDocument)
I found out how to obtain the Diffgram in a string:
// DataSet to Diffgram in a string:
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
ds.WriteXml(xw, XmlWriteMode.WriteSchema);//XmlWriteMode.DiffGram
}
string str = sb.ToString();
but it seems wasteful to first output the xml of a diffgram to a string and then parse it back in to an XElement. So I am trying to find out how to fill in the missing link in this code, which should transfer the xml of the diffgram without conversions to an Xml variable:
// I have a DataSet filled with some data
DataSet ds = new DataSet();
ds.Tables.Add(ScanData);
// I need the diffgram of the DataSet in an XElement
XElement xe = null;
XmlReader xr = xe.CreateReader();
// I could live with output to XDocument, and extract the XElement later
XDocument xd = new XDocument();
XmlReader xrd = xd.CreateReader();
// Q: How do I construct a stream that connects an XmlReader to ds.WriteXml()?
Stream stream = ...???... ;
// This method creates the DiffGram output format to a stream
ds.WriteXml(stream, XmlWriteMode.WriteSchema);//diffgram output
I hope to find the answer to my code problem, and maybe even to learn how stream/reader/writer really work.

You need a writer, not reader, to write from DataSet to XDocument:
XDocument xd = new XDocument();
using (var writer = xd.CreateWriter())
{
ds.WriteXml(writer, XmlWriteMode.WriteSchema); // XmlWriteMode.DiffGram
}

Related

How to show parsed xml in TextBlock in WPF?

I have TextBlock with name XML_View, also I know .xml file location string filename = dlg.FileName;
So I want to show xml n that TextBlock, I found a possible solution here (Display XML in a WPF textbox), it gives as a function, like this:
protected string FormatXml(string xmlString)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
StringBuilder sb = new StringBuilder();
System.IO.TextWriter tr = new System.IO.StringWriter(sb);
XmlTextWriter wr = new XmlTextWriter(tr);
wr.Formatting = Formatting.Indented;
doc.Save(wr);
wr.Close();
return sb.ToString();
}
If I get required string, I might just simply write XML_View.Text = String_xml; or something like this. But I don't know how to get string if I have .xml file and I don't know how to use such a function.
I've modified your function to take as parameter the filename to read your xml from. Make sure the file exists in your bin directory (or you use an absolute path like #"C:\temp\myfile.xml" to resolve).
protected string FormatXml(string xmlFile)
{
XmlDocument doc = new XmlDocument();
FileStream fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
doc.Load(fs);
StringBuilder sb = new StringBuilder();
System.IO.TextWriter tr = new System.IO.StringWriter(sb);
XmlTextWriter wr = new XmlTextWriter(tr);
wr.Formatting = Formatting.Indented;
doc.Save(wr);
wr.Close();
return sb.ToString();
}
You can replace
doc.LoadXml(xmlString);
with
doc.Load(xmlFilePath);
I used this as reference.

XML Serialization to String

I'm trying to serialize an object into a string. Here is the code:
XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, data);
var xml = textWriter.ToString();
This works but "\r\n" are part of the string. I want to perform an XSLT transform with this string. That doesn't work because of the "\r\n" characters.
Here is the transform code:
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltPath);
using (XmlReader xmlReader = System.Xml.XmlReader.Create(new StringReader(xmlString)))
{
transform.Transform(xmlReader, xmlWriter);
...
}
How to I go about this?
Simply replace those \r\ns with \n then use XSLT
var xml = textWriter.ToString().Replace("\r\n", "\n");

Xml entity get removed when load a xml document and save it

i have a xml document that contains entity. when i load it and process and save then all entity get converted into UTF encoding. how to get document same as input content.
Input xml is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter SYSTEM "DTD_v1.5\PLI.dtd">
<chapter num="1" update-date="November 2012" type="chapter">
<page num="3"/>
<title>Artist-Dealer Relations</title>
<para align="left"><content-style font-style="bold">S</content-style>i ­Salander-O’Reilly .</para>
<para>Since that time, the New York state artist consignment statute—which, </para>
<para>The of the artist’s work; the amount o and the like. </para>
<para>But firss of “dealer” and “gallery” interchangeably.</para>
<itemizedlist type="•">
<item><para>To care </para></item>
</itemizedlist>
<chapter>
I want out put also same as the above xml
i have try the following codes
XmlDocument xDoc = new XmlDocument();
string text = string.Empty;
text = ReadFile("38149_Chapter01_Art_Law_XML.xml", enmReadType.None, Encoding.Default);
xDoc.LoadXml(text);
xDoc.Save("38149_Chapter01_Art_Law_XML.xml");
and
string sXmlData = File.ReadAllText("38149_Chapter01_Art_Law_XML.xml", Encoding.Default);
xDoc.LoadXml(sXmlData);
XmlAttribute aa = xDoc.CreateAttribute("Name");
aa.Value = "Sarvesh";
XmlNode snode = xDoc.SelectSingleNode("//chapter");
snode.Attributes.Append(aa);
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-1");
XmlWriter xw = XmlWriter.Create(ms, settings);
xDoc.Save(xw);
xw.Close();
using (TextWriter tx = new StreamWriter("38149_Chapter01_Art_Law_XML.xml", false, Encoding.Default))
{
tx.Write(Encoding.UTF8.GetString(ms.ToArray()));
tx.Close();
}
}

Indentation of XML not working as expected

I am trying to create an XML file using string data. (Which is itself in XML format.) But the main problem is that the XML that I have created is not properly formatted. I have used XmlWriterSettings to format the XML, but it does not seem to be working. Can anyone tell me what is wrong with this code.
string unformattedXml = #"<datas><data1>sampledata1</data1><datas>";
XmlWriterSettings xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true};
using (XmlWriter writer = XmlWriter.Create(Console.Out, xmlSettingsWithIndentation))
{
writer.WriteRaw(unformattedXml);
}
Actually when I load this string in an XmlDocument and then saves it as a file, it was formatted. I just wanted to know why it was not working with XmlWriter.
You help would be much appreciated.
Thanks,
Alex
To ignore white space, try this:
private static string FormatXml(string unformattedXml)
{
//First read the xml, ignoring whitespace.
var readeroptions = new XmlReaderSettings { IgnoreWhitespace = true };
var reader = XmlReader.Create(new StringReader(unformattedXml), readeroptions);
//Then write it out with indentation.
var sb = new StringBuilder();
var xmlSettingsWithIndentation = new XmlWriterSettings { Indent = true };
using (var writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
writer.WriteNode(reader, true);
return sb.ToString();
}
It should work if you use a XmlReader instead of a raw string.
(I expect it is a typo when your last XML element is not closed property, and that by formatting you refer to correct indentation):
class Program
{
static void Main(string[] args)
{
string unformattedXml = #"<datas><data1>sampledata1</data1></datas>";
var rdr = XmlReader.Create(new StringReader(unformattedXml));
var sb = new StringBuilder();
var xmlSettingsWithIndentation = new XmlWriterSettings
{
Indent = true
};
using (var writer = XmlWriter.Create(sb, xmlSettingsWithIndentation))
writer.WriteNode(rdr, true);
Console.WriteLine(sb);
Console.ReadKey();
}
}
It outputs:
<?xml version="1.0" encoding="utf-16"?>
<datas>
<data1>sampledata1</data1>
</datas>
Please cf. similar questions:
XmlWriter.WriteRaw indentation
XML indenting when injecting an XML string into an XmlWriter

When saving an XmlDocument, it ignores the encoding in the XmlDeclaration (UTF8) and uses UTF16

i have the following code:
var doc = new XmlDocument();
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(xmlDeclaration);
XmlElement root = doc.CreateElement("myRoot");
doc.AppendChild(root);
root.InnerText = "myInnerText";
StringWriter sw = new StringWriter();
doc.Save(sw);
Console.WriteLine(sw.ToString());
Console.WriteLine();
MemoryStream ms = new MemoryStream();
doc.Save(ms);
Console.WriteLine(Encoding.ASCII.GetString(ms.ToArray()));
And here is the output:
<?xml version="1.0" encoding="utf-16"?>
<myRoot>myInnerText</myRoot>
???<?xml version="1.0" encoding="UTF-8"?>
<myRoot>myInnerText</myRoot>
Basically what it does is make an xml file, and set the encoding to utf8, but when it saves it to stringwriter it ignores my encoding and uses utf16. However, when using a memory stream, it uses utf8 (with the extra BOM chars)
Why is this? Why isn't it honouring my explicit encoding setting of utf-8?
Thanks a lot
Because all you are doing is setting an XML element that says it's UTF-8, you aren't actually saving it as UTF-8. You need to set the output stream to use UTF-8, like this:
var doc = new XmlDocument();
XmlElement root = doc.CreateElement("myRoot");
doc.AppendChild(root);
root.InnerText = "myInnerText";
using(TextWriter sw = new StreamWriter("C:\\output.txt", false, Encoding.UTF8)) //Set encoding
{
doc.Save(sw);
}
Once you do that, you don't even have to add the XML declaration. It figures it out on its own. If you want to save it to a MemoryStream, use a StreamWriter that wraps the MemoryStream.
I use the following method, it writes it out pretty and as UTF-8
public static string Beautify(XmlDocument doc)
{
string xmlString = null;
using (MemoryStream ms = new MemoryStream()) {
XmlWriterSettings settings = new XmlWriterSettings {
Encoding = new UTF8Encoding(false),
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(ms, settings)) {
doc.Save(writer);
}
xmlString = Encoding.UTF8.GetString(ms.ToArray());
}
return xmlString;
}
Call it like:
File.WriteAllText(fileName, Utilities.Beautify(xmlDocument));
From the MSDN we can see...
The encoding on the TextWriter determines the encoding that is written out (The encoding of the XmlDeclaration node is replaced by the encoding of the TextWriter). If there was no encoding specified on the TextWriter, the XmlDocument is saved without an encoding attribute.
If you want to use the encoding from the XmlDeclaration you'll need to use a stream to save the document.

Categories

Resources