I am trying to parse an XMl document that i received into a string from a web service call.
String content = ...;//long xml document
using(TextReader reader = new StringReader(content))
using(XmlReader xml_reader = XmlReader.Create(reader, settings))
{
XML = new XPathDocument(xml_reader);
}
however i get an exception :
An error occurred while parsing EntityName. Line 1, position 1721.
i looked through the document around that character and it was in the middle of a random tag, however about 20-30 chars earlier i noticed that there were unescaped ampersands (& characters), so im thinking that that is the problem.
running:
content.Substring(1700, 100);//results in the following text
"alue>1 time per day& with^honey~&water\\\\</Value></Frequency></Direction> </Directions> "
^unescaped & char 1721 is the 'w'
how can i successful read this document as xml?
verify that your xml encoding matches theirs (the top of the document, something like <?xml version="1.0" encoding="ISO-8859-9"?>). Substitute the value from the webservice xml document for webserviceEncoding below
using(XmlReader r = XmlReader.Create(new StreamReader(fileName, Encoding.GetEncoding(webserviceEncoding)))) {
XML = new XPathDocument( r );
// ...
}
If that doesn't work
Replace it in the string prior to loading it into an xml parser
Notify the webservice vendor
Related
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);
}
I get a XmlElement from a web service. I get something unexpected because xmlElement.OwnerDocument.ChildNodes is empty. How is that possible?
This is the xml:
<tns1:VideoSource xmlns:tns1="http://www.onvif.org/ver10/topics">
<MotionAlarm wstop:topic="true" xmlns:wstop="http://docs.oasis-open.org/wsn/t-1" xmlns="http://www.onvif.org/ver10/events/wsdl">
</MotionAlarm>
</tns1:VideoSource>
I tested you xml with the code below and there are children like you said. I suspect there may be some white characters that is creating an error. If you got data from a website (probably a stream) there may be some null characters at the end of the stream that is invisible. Make sure your stream class is using UTF8 encoding. The default encoding in some streams is Ascii which can change characters and add padding character which may create issues.
string input =
"<tns1:VideoSource xmlns:tns1=\"http://www.onvif.org/ver10/topics\">" +
"<MotionAlarm wstop:topic=\"true\" xmlns:wstop=\"http://docs.oasis-open.org/wsn/t-1\" xmlns=\"http://www.onvif.org/ver10/events/wsdl\">" +
"</MotionAlarm>" +
"</tns1:VideoSource>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(input);
XmlNodeList videoSource = doc.ChildNodes;
XmlNodeList motionAlarm = videoSource[0].ChildNodes;
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);
}
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);
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.