convert KOI8-R xml node into unicode in c# - c#

I have the following xml:
<root>
<text><![CDATA[ОПЕЛХМЮБЮ ОПЕГ БЗПРЪЫ ЯЕ АЮПЮАЮМ, Б ЙНИРН ЯЕ]]></text>
</root>
I know this text is generated using encoding KOI8-R (this text is displayed in my text editor only when I select this encoding when I open the xml file as text) and I would like to convert the value of this node into a string usable in c#. I can read the InnerText value of this node, but it's not what I'm expecting. Can someone show me the correct way to convert a string written with this encoding into a Unicode one?
Update
Following Jon Skeet suggestions, the solution would look like this:
Encoding encoding = Encoding.GetEncoding("KOI8-R");
XmlDocument doc2 = new XmlDocument();
using (TextReader tr = new StreamReader(outputPath, encoding))
{
doc2.Load(tr);
}

How do you have that XML? It should have an XML declaration stating which encoding it's using; otherwise it's not correct simply in XML terms. You shouldn't be worrying about encodings after you've parsed the XML. So potentially something like:
Encoding encoding = Encoding.GetEncoding("KOI8-R");
XDocument doc;
using (var reader = File.OpenText("file.xml", encoding))
{
doc = XDocument.Load(reader);
}
... but as I say, the file itself should declare the encoding.

Related

XML Illegal Characters in path using XPathDocument to do XSL Transform in C#

I have an XML in a string that I need to actually transform to html using an xsl.
I do the transform with XslCompiledTransform. In order for this to work, I am parsing the string that contains the XML to XML using XPathDocument.
However if I try to parse the string straight to the XPathDocument, then I get the error:
Illegal Characters in path.
So I had to include a StringReader in order to be able to parse the string to the XPathDocument. (Using the solutions in the posts I linked below.)
Here is my step by step procedure:
The string is retrieved from SDL Trados Studio and it depends on the XML that is being worked on (how it was originally created and loaded for translations) the string sometimes has a BOM sometimes not. The 'xml' is actually parsed from the segments of the source and target text and the structure element. The textual elements are escaped for xml and the markup and text is joined in one string. (My separate post on the removal of the BOM is C# XPathDocument parsing string to XML with BOM.)
The the string is then parsed into an XPathDocument using a StringReader.
The transform is done with the XslCompiledTransform, using a StringBuilder and a StringWriter.
Transformed xml (now html) is saved to a file.
Here is my code:
//Recreate XML file using an extractor returns a string array
string strSourceXML = String.Join("", extractor.TextSrc);
//strip BOM
strSourceXML = strSourceXML.Substring(strSourceXML.IndexOf("<?"));
//Transform XML with the preview XSL
var xSourceDoc = new XPathDocument(strSourceXML);
//Load XSL
var xTr = new XslCompiledTransform();
var xslt = Settings.GetValue("WordPreview", "XSLTpath", "");
xTr.Load(xslt);
//Parse XML string
dynamic xSourceDoc;
using (StringReader s = new StringReader(strSourceXML))
{
xSourceDoc = new XPathDocument(s);
}
//Transform the XML
StringBuilder sb1 = new StringBuilder();
StringWriter swSource = new StringWriter(sb1);
xTr.Transform(xSourceDoc, null, swSource);
//Transformed file saved to the disk
string tmpSourceDoc = Path.GetTempFileName();
System.IO.StreamWriter writer1 = new System.IO.StreamWriter(tmpSourceDoc, false, Encoding.Unicode);
writer1.Write(sb1.ToString());
writer1.Close();
My question is: Is there a simpler way to solve it? Any suggestions to transform the string straight using the XSLT? Or if not, is there a direct way to parse a string to the XPathDocument?
I have searched over many posts on Stack Overflow such as these:
XML Illegal Characters in path
Illegal characters in path error while parsing XML in C#
Illegal characters in path when loading a string with XDocument
But none of them give me the solution to do this simpler. Any suggestion is welcome. Thanks.
Don't need the intermediate StringBuilder and StringWriter.
XsltCompiledTransform instance can immediately writes to the stream on disk.
string strSourceXML = string.Concat(extractor.TextSrc);
strSourceXML = strSourceXML.Substring(strSourceXML.IndexOf("<?"));
var xTr = new XslCompiledTransform();
var xslt = Settings.GetValue("WordPreview", "XSLTpath", "");
xTr.Load(xslt);
string tmpSourceDoc = Path.GetTempFileName();
using (var reader = new StringReader(strSourceXML))
using (var writer = new StreamWriter(tmpSourceDoc, false, Encoding.Unicode))
{
var xSourceDoc = new XPathDocument(reader);
xTr.Transform(xSourceDoc, null, writer);
}

XDocument Parse Ignore Chinese Characters

I have a XML string which contains some chinese characters like �菅࿼Ჽ탽᫴. So When Parsing it with XDocument.Parse it is throwing the below exception.
System.Xml.XmlException: '', hexadecimal value 0x01, is an invalid character
I tried converting the xml string to UTF-8. But still the same issue.
Any Ideas?
Update:
XML Contains lots of elements in it, but on using the below answer it is ignoring all the other elements but just converting the elements which has special characters, Is there anything can be done with XDocument instead of XElement?
Use XmlReader with XmlReaderSettings.CheckCharacters set to false will solve your issue.
UPDATE
Here is what I'd used to load my japanese xml file.
string xmlText = "your xml data";
XElement node;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.CheckCharacters = false;
using (XmlReader rd = XmlReader.Create(new StringReader(xmlText), xrs))
{
node = XElement.Load(rd);
}

How Can I Encode My New Xml Document?

I have a string with a XML text and i want to save it like XML. I encoded string (to "utf-8") but when i want to make XML from that - my cyrillic symbols in Value don't displayed right . What i need to do to encode my XML document ?
part of my xml :
<rev:Code>Мои данные</rev:Code>
my code:
string send = Encoding.GetEncoding("utf8").GetString(Encoding.GetEncoding("utf-8").GetBytes(send));
XmlDocument docsec = new XmlDocument();
docsec.LoadXml(send);
docsec.Save("C:\\XmlNEW.xml");
Original text :Мои данные
I see it after creating XML :Мои данные
I worked with russian textfiles before to convert them to rtf and used "Encoding.GetEncoding(1251)" for that purpose.
Problem was in Save Method because it use xml encoding, i take my answer from this : Answer
XmlDocument docsec = new XmlDocument();
docsec.LoadXml(send);
using (TextWriter writer = new StreamWriter("C:\XmlNEW.xml", false, Encoding.UTF8))
docsec.Save(writer);

How change file coding from windows-1251 to utf-8

I have xml file and I need to convert the text that I get from it:
I just start to write code, but I don't know how to realize this:
string text = File.ReadAllText(path);
XDocument documentcode = XDocument.Load(text);
You will have to specify the correct encoding when reading:
string text = File.ReadAllText(path, Encoding.GetEncoding("windows-1251"));
XDocument documentcode = XDocument.Parse(text); // not load.
You probably don't have to do anything special when writing.

Convert XPathDocument to string

I have an XPathDocument and would like to export it in a string that contains the document as XML representation. What is easiest way of doing so?
You can do the following to get a string representation of the XML document:
XPathDocument xdoc = new XPathDocument(#"C:\samples\sampleDocument.xml");
string xml = xdoc.CreateNavigator().OuterXml;
If you want your string to contain a full representation of the XML document including an XML declaration you can use the following code:
XPathDocument xdoc = new XPathDocument(#"C:\samples\sampleDocument.xml");
StringBuilder sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
xdoc.CreateNavigator().WriteSubtree(xmlWriter);
}
string xml = sb.ToString();
An XPathDocument is a read-only representation of an XML document. That means that the internal representation will not change. To get the XML, you can get the original document.
Or use 0xA3's method, which will go through the whole document and write it again (output not necessarily the same as input, yet structurally and functionally equal, because some input is discarded with XDM in-memory representation)

Categories

Resources