Issue while converting string to org.w3c.dom.Element
-
30-06-2021 - |
Question
When I am parsing the string to org.w3c.dom.Element I am getting following exception.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 245; Invalid byte 3 of 3-byte UTF-8 sequence.
Code that I have used to convert string to element is:
public Element convertStringToDoc(String xmlString) throws Exception{
org.w3c.dom.Document doc;
try {
java.io.InputStream sbis = new java.io.StringBufferInputStream(xmlString);
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
b.setNamespaceAware(false);
doc = null;
javax.xml.parsers.DocumentBuilder db = null;
db = b.newDocumentBuilder();
doc = db.parse(sbis);
org.w3c.dom.Element e = doc.getDocumentElement();
return e;
} catch (Exception e1) {
throw e1;
} }
and my input string is:
<?xml version="1.0" encoding="UTF-8"?>
<a id="ctl00_RSContent1_ResultsList_ctl00_ProductTitleLink" href="../Product/the_western_european_wear_tear_parts_market_201115?productid=TD00033-006">The Western European Wear & Tear Parts Market, 2011–15</a>
Solution
In my opinion the java String class is not UTF-8 encoded. It seems the "–" sequence has in java string unicode a byte coding that is not allowed in UTF-8. Change your code like this ...
...
byte[] utf8Bytes=xmlString.getBytes("UTF-8");
java.io.InputStream sbis = new java.io.ByteArrayInputStream(utf8Bytes);
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow