I got some trouble parsing an XML document. For some reason, there are text nodes where I would not expect them to be and therefore my test turns red. The XML file looks like this:
PR1
one
two
DG1
three
ZBK
four
Now I have this snippet of code which can reproduce the error:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(TestHL7Helper.class.getResourceAsStream("TestHL7HelperInput.xml"));
Node root = doc.getFirstChild();
Node pr1 = root.getFirstChild();
Inspecting the root variable yields [RootNode: null] which seems to be right, but then it somehow goes all wrong. The pr1 variable turns out to be a text node [#text:\n ] - but why does the parser think that the new line and the spaces are a text node? Shouldn't that be ignored? I tried changing the encoding but that did not help either. Any ideas on that?
If I remove all new lines and space and have my XML document in just one line it all works fine...
解决方案
XML supports mixed content meaning elements can have both text and element child nodes. This is to support use cases like the following:
I've bolded the important part.
input.xml
This means that by default a DOM parser will treat the whitespace nodes in the following document as significant (below is a simplified version of your XML document):
PR1
Demo Code
If you have an XML schema you can set the ignoringElementContentWhitespace property on the DocumentBuilderFactory since then the DOM parser will know if and when the whitespace is significant.
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.*;
import javax.xml.validation.*;
import org.w3c.dom.Document;
public class Demo {
public static void main(String[] args) throws Exception {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema s = sf.newSchema(new File("src/forum16231687/schema.xsd"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setSchema(s);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(new File("src/forum16231687/input.xml"));
System.out.println(d.getDocumentElement().getChildNodes().getLength());
}
}
schema.xsd
If you create schema.xsd that looks like the following then the demo code will report that the root element has 1 child node.
If you change schema.xsd so that the RootNode has mixed content the demo code will report that the RootNode has 3 child nodes.