RDLC Display a formatted Xml string - c#

I need to format my xml string to display it in RDLC report, arranged by tags. Something like
<Root>
<Child>
<SubChild>...</SubChild>
</Child>
</Root>
I can't seem to find a way to do that, other than just iterating through the string horribly and trying to arrange it manually. Is there a way to do it with some format function in RDLC or in some other way and pass it to RDLC already formatted?

You can use this function to format your XML strings outside RDLC.
You need to use XMLWriterSettings.OmitXmlDeclaration to save an indented XML without declaration line (i.e.: <?xml version="1.0" encoding="utf-16"?>)
Dim strXML As String = "<Root><Child><SubChild>test</SubChild></Child></Root>"
Dim xmlDoc As New System.Xml.XmlDocument
xmlDoc.LoadXml(strXML)
Dim xmlSettings As New System.Xml.XmlWriterSettings
xmlSettings.Indent = True
xmlSettings.OmitXmlDeclaration = True
Dim sb As New System.Text.StringBuilder
Using writer As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(sb, xmlSettings)
xmlDoc.Save(writer)
End Using
MsgBox(sb.ToString())

Related

How would one add a string value to a newly created xml file in c#?

In my code I'm creating a new xml file with linq to xml and I have a specific format of xml that I'm trying to put into the xml file on creation. However, when I put the string variable in it gives the error "non white space characters cannot be added to content." How would I correctly add that string value to the xml file?
string firstPart = #"<?xml version=""1.0"" encoding=""utf-8""?>
< wiidisc version = ""1"" >
< id game = ""RMCE"" disc = ""0"" version = ""0"" >
</ id > ";
XDocument doc = new XDocument(firstPart);
doc.Save(riivolutionXmls + #"\" + xmlFileName + ".xml");
This isn't valid XML, you're missing a closing tag for wiidisc.
Also I don't think you can use the constructor to create an XDocument from a string, I think you have to use the XDocument.Parse method:
https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.parse?view=netframework-4.7.2#System_Xml_Linq_XDocument_Parse_System_String_

xml string change the header encoding using c#

I have string of XML .
how can I change the header from:
string xml = "<?xml version='1.0' encoding='ISO-8859-8'?>";
to
string xml = "<?xml version='1.0' encoding='UTF-8'?>";
using c#?
UPDATE
I tryed to get the xml to User object
XmlSerializer serializer = new XmlSerializer(typeof(User));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
User user = (User)serializer.Deserialize(memStream);
but in the User object I get the string not encoding well.
because of the encoding of the Xml I need to change the encoding.
Instead of Encoding.UTF8.GetBytes use Encoding.GetEncoding("ISO-8859-8").GetBytes.
If the XML is stored in a string variable and you need to only replace the value in the encoding attribute, then you can perform a replace as following:
const string searchEncoding = "ISO-8859-8";
const string newEncoding = "UTF-8";
string xml = #"<?xml version='1.0' encoding='ISO-8859-8'?><abc></abc>";
int encodingPos = xml.IndexOf(searchEncoding);
if (encodingPos==30)
{
xml = xml.Substring(0, encodingPos) + newEncoding + xml.Substring(encodingPos + searchEncoding.Length);
}
However, a different process is necessary if the XML is stored in another datatype and/or you need to re-encode the XML content.

IgnoreWhiteSpace not ignoring whitespace at beginning of xml string

Question
Should whitespace be ignored at the beginning of my multi-line string literal xml?
Code
string XML = #"
<?xml version=""1.0"" encoding=""utf-8"" ?>"
using (StringReader stringReader = new StringReader(XML))
using (XmlReader xmlReader = XmlReader.Create(stringReader,
new XmlReaderSettings() { IgnoreWhitespace = true }))
{
xmlReader.MoveToContent();
// further implementation withheld
}
Notice in the above code that there is white space before the XML declaration, this doesn't seem to be being ignored despite my setting of the IgnoreWhiteSpace property. Where am I going wrong?!
Note: I have the same behaviour when the XML string does not have a line break, and just a whitespace, as below. I know this will run if I remove the whitespace, my question is as to why the property doesn't take care of this?
string XML = #" <?xml version=""1.0"" encoding=""utf-8"" ?>"
The documentations say that the IgnoreWhitespace property will "Gets or sets a value indicating whether to ignore insignificant white space.". While that first whitespace (and also linebreak) should be insignificant, the one who made XmlReader apparently didn't think so. Just trim XML before use, and you'll be fine.
As stated in comments and for clarity, change your code to:
string XML = #"<?xml version=""1.0"" encoding=""utf-8"" ?>"
using (StringReader stringReader = new StringReader(XML.Trim()))
using (XmlReader xmlReader = XmlReader.Create(stringReader,
new XmlReaderSettings() { IgnoreWhitespace = true }))
{
xmlReader.MoveToContent();
// further implementation withheld
}
According to Microsoft's documentation regarding XML Declaration
The XML declaration typically appears as the first line in an XML
document. The XML declaration is not required, however, if used it
must be the first line in the document and no other content or white
space can precede it.
The parse should fail for your code because white space precedes the XML declaration. Removing either the white space OR the xml declaration will result in a successful parse.
In other words it would be a bug if XmlReaderSettings were at odds with the documentation for XML Declaration - it is defined behavior.
Here's some code demonstrating the above rules.
using System;
using System.Web;
using System.Xml;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
//The XML declaration is not required, however, if used it must
// be the first line in the document and no other content or
//white space can precede it.
// here, no problem because this does not have an XML declaration
string xml = #"
<xml></xml>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc.Document.Declaration);
Console.WriteLine(doc.Document);
//
// problem here because this does have an XML declaration
//
xml = #"
<?xml version=""1.0"" encoding=""utf-8"" ?><xml></xml>";
try
{
doc = XDocument.Parse(xml);
Console.WriteLine(doc.Document.Declaration);
Console.WriteLine(doc.Document);
} catch(Exception e) {
Console.WriteLine(e.Message);
}
}
}

richTextbox1 to textbox1?

I have this text in a rich text box named richTextBox:
<notification_counts>
<unseen>0</unseen>
</notification_counts>
<friend_requests_counts>
<unread>1</unread>
<unseen>**0**</unseen>
</friend_requests_counts>
I would like to extract the value from the unseen tag (0 in this example) and place it in the text box named textbox1. How should I go about doing this?
Full code
<?xml version="1.0" encoding="UTF-8"?>
<notifications_get_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd">
<messages>
<unread>0</unread>
<unseen>0</unseen>
<most_recent>****</most_recent>
</messages>
<pokes>
<unread>0</unread>
<most_recent>0</most_recent>
</pokes>
<shares>
<unread>0</unread>
<most_recent>0</most_recent>
</shares>
<notification_counts>
<unseen>0</unseen>
</notification_counts>
<friend_requests_counts>
<unread>1</unread>
<unseen>0</unseen>
</friend_requests_counts>
<friend_requests list="true">
<uid>***</uid>
</friend_requests>
<group_invites list="true"/>
<event_invites list="true"/>
</notifications_get_response>
If your rich text box only contains XML markup, you can parse it to extract the value you're interested in. For instance, using LINQ to XML:
using System.Xml.Linq;
textBox1.Text = XElement.Parse(richTextBox.Text)
.Descendant("friend_requests_counts")
.Element("unseen").Value;
EDIT: Since your XML markup contains namespaces, you have to take them into account when selecting the elements:
XNamespace fb = "http://api.facebook.com/1.0/";
textBox1.Text = XDocument.Parse(richTextBox.Text).Root
.Element(fb + "friend_requests_counts")
.Element(fb + "unseen").Value;

Using XDocument to write raw XML

I'm trying to create a spreadsheet in XML Spreadsheet 2003 format (so Excel can read it). I'm writing out the document using the XDocument class, and I need to get a newline in the body of one of the <Cell> tags. Excel, when it reads and writes, requires the files to have the literal string
embedded in the string to correctly show the newline in the spreadsheet. It also writes it out as such.
The problem is that XDocument is writing CR-LF (\r\n) when I have newlines in my data, and it automatically escapes ampersands for me when I try to do a .Replace() on the input string, so I end up with &#10; in my file, which Excel just happily writes out as a string literal.
Is there any way to make XDocument write out the literal
as part of the XML stream? I know I can do it by deriving from XmlTextWriter, or literally just writing out the file with a TextWriter, but I'd prefer not to if possible.
I wonder if it might be better to use XmlWriter directly, and WriteRaw?
A quick check shows that XmlDocument makes a slightly better job of it, but xml and whitespace gets tricky very quickly...
I battled with this problem for a couple of days and finally came up with this solution. I used XMLDocument.Save(Stream) method, then got the formatted XML string from the stream. Then I replaced the &#10; occurrences with
and used the TextWriter to write the string to a file.
string xml = "<?xml version=\"1.0\"?><?mso-application progid='Excel.Sheet'?><Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
xml += "<Styles><Style ss:ID=\"s1\"><Alignment ss:Vertical=\"Center\" ss:WrapText=\"1\"/></Style></Styles>";
xml += "<Worksheet ss:Name=\"Default\"><Table><Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"75\" /><Row><Cell ss:StyleID=\"s1\"><Data ss:Type=\"String\">Hello&#10;&#10;World</Data></Cell></Row></Table></Worksheet></Workbook>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml); //load the xml string
System.IO.MemoryStream stream = new System.IO.MemoryStream();
doc.Save(stream); //save the xml as a formatted string
stream.Position = 0; //reset the stream position since it will be at the end from the Save method
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string formattedXML = reader.ReadToEnd(); //fetch the formatted XML into a string
formattedXML = formattedXML.Replace("&#10;", "
"); //Replace the unhelpful &#10;'s with the wanted endline entity
System.IO.TextWriter writer = new System.IO.StreamWriter("C:\\Temp\test1.xls");
writer.Write(formattedXML); //write the XML to a file
writer.Close();

Categories