Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - What is the property IS_COALESCING in XMLInputFactory for?

I don't really understand the definition from the Oracle documentation:

The property that requires the parser to coalesce adjacent character data sections

I've tried a few examples with both this property to true and false, and there don't seem to be any noticeable changes.

Can anyone please provide me with a better explanation and maybe an example in which it matters?

question from:https://stackoverflow.com/questions/66064967/what-is-the-property-is-coalescing-in-xmlinputfactory-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It can e.g. make a difference if the text content of an element is a mix of plain &-encoded text, and CDATA-encoded text.

Demo

public static void main(String[] args) throws Exception {
    test(false);
    test(true);
}
static void test(boolean coalesce) throws Exception {
    System.out.println("IS_COALESCING = " + coalesce + ":");
    String xml = "<Root>abc<![CDATA[def]]>ghi</Root>";
    
    XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, coalesce);
    XMLEventReader reader = xmlInputFactory.createXMLEventReader(new StringReader(xml));
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isCharacters())
            System.out.println("  "" + event.asCharacters().getData() + """);
    }
}

Output

IS_COALESCING = false:
  "abc"
  "def"
  "ghi"
IS_COALESCING = true:
  "abcdefghi"

If you parsed into DOM, the <Root> element would have 3 Node children:

  • Text where getData() returns "abc"
  • CDATASection where getData() returns "def"
  • Text where getData() returns "ghi"

The XMLInputFactory property works the same as the DocumentBuilderFactory.setCoalescing(boolean coalescing) method:

Specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node. By default the value of this is set to false


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...