I am writing some code that talks to a legacy system that needs the following element:

<BankRate><![CDATA[        ]]><BankRate>

I can't for the life of me get this working, my attempt so far is:

parent.setBankRate("    ");
XmlCursor cursor = cc.xgetBankRate().newCursor();
cursor.toFirstContentToken();
cursor.setBookmark(CDataBookmark.CDATA_BOOKMARK);
cursor.dispose();

This simply results in the following:

<BankRate><BankRate>

The options for the parent is: setSaveCDataEntityCountThreshold(0).setSaveCDataLengthThreshold(0);

If I setBankRate like the following:

cc.setBankRate("<![CDATA[        ]]>");

I get character entities (which is not what I want)

有帮助吗?

解决方案

I tried the following test:

import org.apache.xmlbeans.*;

public class main {
    public static void main ( String[] args ) throws XmlException {
        XmlObject x = XmlObject.Factory.parse( "<BankRate>        </BankRate>" );
        XmlCursor c = x.newCursor();
        c.toFirstContentToken();
        c.toNextToken();
        c.setBookmark(CDataBookmark.CDATA_BOOKMARK);
        XmlOptions options = new XmlOptions();
        options.setSaveCDataLengthThreshold( 1 );
        options.setUseCDataBookmarks();
        System.out.print( x.xmlText( options ) );
    }
}

The result is:

<BankRate><![CDATA[        ]]></BankRate>

If your goal is to force the saving of the contents of BankRate as CDATA, this is how you do it.

However, if this does not work, and you get nothing (the empty element) as the value of BankRate, then what is probably happening is that the BankRate Type is not text, and is some other type which ignores white space. If you really need to get whitespace as the value of BankRate, you will have to inject it with an XmlCursor.

其他提示

So, I'm trying to recreate your scenario. Here is a simple schema with an element which is of the string type.

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Moo" type="xs:string">
  </xs:element>
</xs:schema>

And here is a program which instantiates the type, sets the value to a few spaces and saves it.

import org.apache.xmlbeans.*;
import noNamespace.*;

public class main {
    public static void main ( String[] args ) throws XmlException {
        MooDocument moo = MooDocument.Factory.newInstance();
        moo.setMoo( "     " );
        System.out.print( moo.xmlText() );
    }
}

The result is:

<Moo>     </Moo>

You can force CDATA by injecting a CDATA bookmark before the text. In your problem, the spaces seem to be missing. How does this differ from your problem?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top