Native Java API for Checking Valid XML - java

How do you determine whether a Document object in Java contains valid XML. Is this checked when the object is constructed?
I can't appear to find any information on this in
http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Document.html
How do you determine whether you have a valid XML Document without using external libraries?
Note: I received this Document object by parsing from an input stream with a DOM XML parser.

Use the Java DOM API. It can handle any valid XML document. A valid document will give no exception. You need no external libraries for DOM.
In case of an error the exception message looks like this:
[Fatal Error] MyXMLFile.xml:6:2: The end-tag for element type "lastname" must end with a '>' delimiter.
The end-tag for element type "lastname" must end with a '>' delimiter.
BUILD SUCCESSFUL (total time: 0 seconds)

Related

JSON parsing using StAXON - XMLStreamException when there is a : character in element name

We are using StAXON (due to its performance via StAX processing) to parse json input which contains colon(:) as element name. Colon is valid element name in JSON but while parsing via StAXON we are getting exception (XMLStreamException).
It works if I use namespaceSeparator as '\0', like new JsonXMLConfigBuilder().namespaceSeparator(Character.MIN_VALUE). But this just changes the namespace separator.
My Question/Doubt:
Is it safe to do this? Are there chances of getting issue(s)
Is there a way to ignore colon while parsing (reading/writing) JSON?
Is there any other alternative to StAXON to parse JSON based on events like StAX parsing is done for XML.
Sample Input : {"cust:person":{"name":"John Doe","phone":"555-1111"}}
Exception
Exception in thread "main" javax.xml.stream.XMLStreamException: Unbound prefix: cust
at de.odysseus.staxon.base.AbstractXMLStreamScope.verify(AbstractXMLStreamScope.java:212)
at de.odysseus.staxon.base.AbstractXMLStreamScope.setStartTagClosed(AbstractXMLStreamScope.java:234)
at de.odysseus.staxon.base.AbstractXMLStreamReader.ensureStartTagClosed(AbstractXMLStreamReader.java:191)
at de.odysseus.staxon.base.AbstractXMLStreamReader.readStartElementTag(AbstractXMLStreamReader.java:272)
at de.odysseus.staxon.json.JsonXMLStreamReader.readStartElementTag(JsonXMLStreamReader.java:93)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:202)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:153)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:183)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:153)
at de.odysseus.staxon.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:183)
at de.odysseus.staxon.base.AbstractXMLStreamReader.initialize(AbstractXMLStreamReader.java:216)
at de.odysseus.staxon.json.JsonXMLStreamReader.initialize(JsonXMLStreamReader.java:87)
at de.odysseus.staxon.json.JsonXMLStreamReader.(JsonXMLStreamReader.java:78)
at de.odysseus.staxon.json.JsonXMLInputFactory.createXMLStreamReader(JsonXMLInputFactory.java:150)
at de.odysseus.staxon.json.JsonXMLInputFactory.createXMLStreamReader(JsonXMLInputFactory.java:45)
at JsonXml.main(JsonXml.java:27)
Thanks
Colon is a legal name character in case the parser is not namespace aware. You should be able to turn off namespace awareness on the underlying XMLInputFactory (don't know the details of StAXON).
It’s safe to do this but it’s probably not what you want. Since StAXON tries to treat JSON like XML, you should give the library what it wants: A namespace for the „cust“ prefix. Read about StAXON‘s conventions here.
To declare a namespace:
new JsonXMLConfigBuilder().namespaceMapping(„cust“, „http://example.com/ns/cust“)

Is there any way to process my rest of xml file despite of any fatal error like SAXParserException encountered [duplicate]

Currently, I'm working on a feature that involves parsing XML that we receive from another product. I decided to run some tests against some actual customer data, and it looks like the other product is allowing input from users that should be considered invalid. Anyways, I still have to try and figure out a way to parse it. We're using javax.xml.parsers.DocumentBuilder and I'm getting an error on input that looks like the following.
<xml>
...
<description>Example:Description:<THIS-IS-PART-OF-DESCRIPTION></description>
...
</xml>
As you can tell, the description has what appears to be an invalid tag inside of it (<THIS-IS-PART-OF-DESCRIPTION>). Now, this description tag is known to be a leaf tag and shouldn't have any nested tags inside of it. Regardless, this is still an issue and yields an exception on DocumentBuilder.parse(...)
I know this is invalid XML, but it's predictably invalid. Any ideas on a way to parse such input?
That "XML" is worse than invalid – it's not well-formed; see Well Formed vs Valid XML.
An informal assessment of the predictability of the transgressions does not help. That textual data is not XML. No conformant XML tools or libraries can help you process it.
Options, most desirable first:
Have the provider fix the problem on their end. Demand well-formed XML. (Technically the phrase well-formed XML is redundant but may be useful for emphasis.)
Use a tolerant markup parser to cleanup the problem ahead of parsing as XML:
Standalone: xmlstarlet has robust recovering and repair capabilities credit: RomanPerekhrest
xmlstarlet fo -o -R -H -D bad.xml 2>/dev/null
Standalone and C/C++: HTML Tidy works with XML too. Taggle is a port of TagSoup to C++.
Python: Beautiful Soup is Python-based. See notes in the Differences between parsers section. See also answers to this question for more
suggestions for dealing with not-well-formed markup in Python,
including especially lxml's recover=True option.
See also this answer for how to use codecs.EncodedFile() to cleanup illegal characters.
Java: TagSoup and JSoup focus on HTML. FilterInputStream can be used for preprocessing cleanup.
.NET:
XmlReaderSettings.CheckCharacters can
be disabled to get past illegal XML character problems.
#jdweng notes that XmlReaderSettings.ConformanceLevel can be set to
ConformanceLevel.Fragment so that XmlReader can read XML Well-Formed Parsed Entities lacking a root element.
#jdweng also reports that XmlReader.ReadToFollowing() can sometimes
be used to work-around XML syntactical issues, but note
rule-breaking warning in #3 below.
Microsoft.Language.Xml.XMLParser is said to be “error-tolerant”.
Go: Set Decoder.Strict to false as shown in this example by #chuckx.
PHP: See DOMDocument::$recover and libxml_use_internal_errors(true). See nice example here.
Ruby: Nokogiri supports “Gentle Well-Formedness”.
R: See htmlTreeParse() for fault-tolerant markup parsing in R.
Perl: See XML::Liberal, a "super liberal XML parser that parses broken XML."
Process the data as text manually using a text editor or
programmatically using character/string functions. Doing this
programmatically can range from tricky to impossible as
what appears to be
predictable often is not -- rule breaking is rarely bound by rules.
For invalid character errors, use regex to remove/replace invalid characters:
PHP: preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $s);
Ruby: string.tr("^\u{0009}\u{000a}\u{000d}\u{0020}-\u{D7FF}\u{E000‌​}-\u{FFFD}", ' ')
JavaScript: inputStr.replace(/[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm, '')
For ampersands, use regex to replace matches with &: credit: blhsin, demo
&(?!(?:#\d+|#x[0-9a-f]+|\w+);)
Note that the above regular expressions won't take comments or CDATA
sections into account.
A standard XML parser will NEVER accept invalid XML, by design.
Your only option is to pre-process the input to remove the "predictably invalid" content, or wrap it in CDATA, prior to parsing it.
The accepted answer is good advice, and contains very useful links.
I'd like to add that this, and many other cases of not-wellformed and/or DTD-invalid XML can be repaired using SGML, the ISO-standardized superset of HTML and XML. In your case, what works is to declare the bogus THIS-IS-PART-OF-DESCRIPTION element as SGML empty element and then use eg. the osx program (part of the OpenSP/OpenJade SGML package) to convert it to XML. For example, if you supply the following to osx
<!DOCTYPE xml [
<!ELEMENT xml - - ANY>
<!ELEMENT description - - ANY>
<!ELEMENT THIS-IS-PART-OF-DESCRIPTION - - EMPTY>
]>
<xml>
<description>blah blah
<THIS-IS-PART-OF-DESCRIPTION>
</description>
</xml>
it will output well-formed XML for further processing with the XML tools of your choice.
Note, however, that your example snippet has another problem in that element names starting with the letters xml or XML or Xml etc. are reserved in XML, and won't be accepted by conforming XML parsers.
IMO these cases should be solved by using JSoup.
Below is a not-really answer for this specific case, but found this on the web (thanks to inuyasha82 on Coderwall). This code bit did inspire me for another similar problem while dealing with malformed XMLs, so I share it here.
Please do not edit what is below, as it is as it on the original website.
The XML format, requires to be valid a unique root element declared in the document.
So for example a valid xml is:
<root>
<element>...</element>
<element>...</element>
</root>
But if you have a document like:
<element>...</element>
<element>...</element>
<element>...</element>
<element>...</element>
This will be considered a malformed XML, so many xml parsers just throw an Exception complaining about no root element. Etc.
In this example there is a solution on how to solve that problem and succesfully parse the malformed xml above.
Basically what we will do is to add programmatically a root element.
So first of all you have to open the resource that contains your "malformed" xml (i. e. a file):
File file = new File(pathtofile);
Then open a FileInputStream:
FileInputStream fis = new FileInputStream(file);
If we try to parse this stream with any XML library at that point we will raise the malformed document Exception.
Now we create a list of InputStream objects with three lements:
A ByteIputStream element that contains the string: <root>
Our FileInputStream
A ByteInputStream with the string: </root>
So the code is:
List<InputStream> streams =
Arrays.asList(
new ByteArrayInputStream("<root>".getBytes()),
fis,
new ByteArrayInputStream("</root>".getBytes()));
Now using a SequenceInputStream, we create a container for the List created above:
InputStream cntr =
new SequenceInputStream(Collections.enumeration(str));
Now we can use any XML Parser library, on the cntr, and it will be parsed without any problem. (Checked with Stax library);

Is there any handy way to inspect whether a xml file contins invalid characters

I am writing a Java program that parses/unmarshals XML files to Java objects.
This program takes XML files, which are generated by some third party and I do not have any control over of.
Upon getting the files, the program checks whether they are invalid format using their respective XSDs↓
URL schemaFile = this.getClass().getClassLoader().getResource(xsd/some.xsd);
Source xmlFile = new StreamSource(new File(/path/to/xml));
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
then starts parsing/unmarshalling them individually using JAXP.
The problem I am facing is that even after the validation above, sometimes I get the following error. (the validator above does not seem to check whether the XML contains invalid characters, but only compare the input with its XSD)
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[xxx,xxx]
Is there any handy way to inspect whether XML file contains invalid characters using programmatically or some tool?
I have extracted the portion(line 245) where the exception occurs using "sed -n '240,250p'".
sample.xml
Do you have a whitelist of allowed characters? Here's one pattern:
For each streamed character, if it is not whitelisted replace it with nothing.
Ask whether your file content after filtering is the same as before (diff pattern)
If the content in both files is not equal then the source file had invalid characters.

JAXB Getting error While parsing the XML

While parsing the XML using JAXB am getting error as "javax.xml.bind.UnmarshalException: An invalid XML character (Unicode: 0xffffffff) was found in the element content of the document " . Because in my xml node have some special characters like "TRÊS2115". How to handle this scenario. I need that special character values too.
This is a problem with your input data. The accented character needs to be escaped within the XML file. The code that wrote the file failed to properly encode the character.

SAXParseException when trying to print data in table

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'jr:table'. One of '{"http://jasperreports.sourceforge.net/jasperreports":component}' is expected.
Why it occurs?
you provide almost no context for your question, so your chances of getting a helpful answer are slim.
however, that looks like the sort of exception you would get if you are parsing an xml document with a schema defined and the document does not match the schema.
UPDATE:
based on your comment below, i see the document does list a schema, so my original guess still stands. your xml document does not match the schema (e.g. there is a "table" element where the schema says there should be a "component" element).

Categories

Resources