JAXB Annotation binding XML content as String - java

I want to bind a XML content as a String to the field.
Here is how my xml seems like:
<sample>
<content>
<p>here is content <b>with bold</b></p>
</content>
</sample>
which should be bound to the following domain object:
#Entity
#Table(name="news_table")
#XmlRootElement
class Sample {
#XmlElement(name="content")
#Column(name="news_content")
private String content;
}
After unmarshalling, i want to bind the content starts with <p> as String type in order to persist formatted text with HTML tags, so that:
System.out.println(sample.getContent());
must give the following out:
> "<p>here is content <b>with bold</b></p>"
With #XmlElement annotation i get only empty string "" back from binding operation, since the JAXB recognize the element starts with "<p>" as Object to be bound according to my understanding.
Any suggestion ?

Try using #XmlAnyElement annotation with a custom DomHandler. You can find an example here.

If it is an option to change the content of the xml file, you could just escape the < and >. Then JAXB handles it just fine and you also get the correct html string when calling getContent() in java.
Here is your xml file with escaped content:
<sample>
<content><p>here is content <b>with bold</b></p></content>
</sample>

Related

request.getParameter - unable reading &

I have a problem reading a value that contains '&' from the url using java spring.
My summary.jsp file contains the following code:
`
<h3>
<fmt:message key="contact.title"/>
<c:if test="${!editMode}">
<label class="eightyfivefont">
<a class="termslink eightyfivefont"
href="?submitForm=true&
institutionName=<c:out value="${institution.institutionName}" />&
repositoryName=<c:out value="${institution.repositoryName}" />&
editMode=true">
(edit)</a>
</label>
</c:if>
</h3>
`
which produce the following url:
...summary.html?submitForm=true&institutionName=r&r&repositoryName=r&r
The problem is when I am trying to fetch the institutionName that hold the value "r&r".
when fetching the value using the following command:
String name = request.getParameter("institutionName");
it fetches only the string "r" and not "r&r".
The string is stored in XML file as "<institutionName>r&r</institutionName>" which is parsed and added using:
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("institution");
and for reading from the xml:
Document doc = DocumentHelper.parseText(xml);
Element root = doc.getRootElement();
(I assume the issue isn't with the XML).
Is there a solution for this problem?
The ampersand & is used to divide key-value pairs. If you want to have it as a value, or key, for that matter, you have to urlencode it. For example, like this:
encodeURIComponent('&') = "%26"
You should be able to use JavaScript for that. Or, of course, some Java method, if the URL is being created in the jsp itself.
You should use URLEncoder to encode the institutionName
java.net.URLEncoder.encode("r&r", "UTF-8")
this outputs the URL-encoded, which is fine as a GET parameter:
r%26r
check this answer. Create a custom EL function or otherwise you can use scriptlet though it is not recommended.

JAXB unmarshal deletes newline

I have a string with newlines in an attribute parameter :
<rule-parameter formattingMethod="NO_FORMATTING_METHOD" type="String" value="Hello,
My name is luba.
How are you?"/>
When I unmarshal this xml the object that I get for this property the string is in one line.
What should I do so the java property will also have newline in the string ?
An XML parser (including JAXB) will not preserve a newline in an XML attribute.
http://www.w3.org/TR/REC-xml/#sec-line-ends
You will need to move this content to an XML element instead.

JAXB facilities in unmarshaling

Hello guys how can i unmarshall list of objects in XML. My XML will be like this
<messageContainer class="class1">
<a>
<b />
</a>
<MessageB />
</messageContainer>
<messageContainer class="class2">
<a>
<b />
</a>
<MessageB />
</messageContainer>
And i want to get list of object in the end.
Any Valid XML file can contain only one XML Root Element.
I assume that u have the above list as a child of an RootElement(say ).
Then your annotated RootElement class should look like this.
#XmlRootElement(name = "RootElement")
public class RootElement{
#XmlElement(name = "messageContainer", required = true)
private List<messageContainer> containerList;
}
Where MessageContainer is a class by itself.
Note : The more simpler way to generate these binding class is, write XSD(or generate using online tools) for your XML and compile those XSD with XJC compiler.

how to get the value of attribute processing by STAX using java language?

i want to get the value of attribute of xml file without knowing it's index, since attributes are repeated in more than one element in the xml file.
here is my xml file
<fields>
<form name="userAdditionFrom">
</form>
</fields>
and here is the procssing file
case XMLEvent.ATTRIBUTE:
//how can i know the index of attribute?
String attName = xmlReader.getAttributeValue(?????);
break;
thanx in advance.
Alaa
If it is XMLStreamReader then getAttributeValue(int index) and getAttributeValue(String namespaceURI, String localName) can be used to get attribute value.
From your question it look like you are using mix of Event and Cursor API. I have appended Using StAX link for your reference that gives idea how to use both.
Resources:
XMLStreamReader getAttributeValue(String, String) JavaDoc Entry
Using StAX

Java XML DOM: how are id Attributes special?

The javadoc for the Document class has the following note under getElementById.
Note: Attributes with the name "ID" or "id" are not of type ID unless so defined
So, I read an XHTML doc into the DOM (using Xerces 2.9.1).
The doc has a plain old <p id='fribble'> in it.
I call getElementById("fribble"), and it returns null.
I use XPath to get "//*[id='fribble']", and all is well.
So, the question is, what causes the DocumentBuilder to actually mark ID attributes as 'so defined?'
These attributes are special because of their type and not because of their name.
IDs in XML
Although it is easy to think of attributes as name="value" with the value is being a simple string, that is not the full story -- there is also an attribute type associated with attributes.
This is easy to appreciate when there is an XML Schema involved, since XML Schema supports datatypes for both XML elements and XML attributes. The XML attributes are defined to be of a simple type (e.g. xs:string, xs:integer, xs:dateTime, xs:anyURI). The attributes being discussed here are defined with the xs:ID built-in datatype (see section 3.3.8 of the XML Schema Part 2: Datatypes).
<xs:element name="foo">
<xs:complexType>
...
<xs:attribute name="bar" type="xs:ID"/>
...
</xs:complexType>
</xs:element>
Although DTD don't support the rich datatypes in XML Schema, it does support a limited set of attribute types (which is defined in section 3.3.1 of XML 1.0). The attributes being discussed here are defined with an attribute type of ID.
<!ATTLIST foo bar ID #IMPLIED>
With either the above XML Schema or DTD, the following element will be identified by the ID value of "xyz".
<foo bar="xyz"/>
Without knowing the XML Schema or DTD, there is no way to tell what is an ID and what is not:
Attributes with the name of "id" do not necessarily have an attribute type of ID; and
Attributes with names that are not "id" might have an attribute type of ID!
To improve this situation, the xml:id was subsequently invented (see xml:id W3C Recommendation). This is an attribute that always has the same prefix and name, and is intended to be treated as an attribute with attribute type of ID. However, whether it does will depend on the parser being used is aware of xml:id or not. Since many parsers were initially written before xml:id was defined, it might not be supported.
IDs in Java
In Java, getElementById() finds elements by looking for attributes of type ID, not for attributes with the name of "id".
In the above example, getElementById("xyz") will return that foo element, even though the name of the attribute on it is not "id" (assuming the DOM knows that bar has an attribute type of ID).
So how does the DOM know what attribute type an attribute has? There are three ways:
Provide an XML Schema to the parser (example)
Provide a DTD to the parser
Explicitly indicate to the DOM that it is treated as an attribute type of ID.
The third option is done using the setIdAttribute() or setIdAttributeNS() or setIdAttributeNode() methods on the org.w3c.dom.Element class.
Document doc;
Element fooElem;
doc = ...; // load XML document instance
fooElem = ...; // locate the element node "foo" in doc
fooElem.setIdAttribute("bar", true); // without this, 'found' would be null
Element found = doc.getElementById("xyz");
This has to be done for each element node that has one of these type of attributes on them. There is no simple built-in method to make all occurrences of attributes with a given name (e.g. "id") be of attribute type ID.
This third approach is only useful in situations where the code calling the getElementById() is separate from that creating the DOM. If it was the same code, it already has found the element to set the ID attribute so it is unlikely to need to call getElementById().
Also, be aware that those methods were not in the original DOM specification. The getElementById was introduced in DOM level 2.
IDs in XPath
The XPath in the original question gave a result because it was only matching the attribute name.
To match on attribute type ID values, the XPath id function needs to be used (it is one of the Node Set Functions from XPath 1.0):
id("xyz")
If that had been used, the XPath would have given the same result as getElementById() (i.e. no match found).
IDs in XML continued
Two important features of ID should be highlighted.
Firstly, the values of all attributes of attribute type ID must be unique to the whole XML document. In the following example, if personId and companyId both have attribute type of ID, it would be an error to add another company with companyId of id24601, because it will be a duplicate of an existing ID value. Even though the attribute names are different, it is the attribute type that matters.
<test1>
<person personId="id24600">...</person>
<person personId="id24601">...</person>
<company companyId="id12345">...</company>
<company companyId="id12346">...</company>
</test1>
Secondly, the attributes are defined on elements rather than the entire XML document. So attributes with the same attribute name on different elements might have different attribute type properties. In the following example XML document, if only alpha/#bar has an attribute type of ID (and no other attribute was), getElementById("xyz") will return an element, but getElementById("abc") will not (since beta/#bar is not of attribute type ID). Also, it is not an error for the attribute gamma/#bar to have the same value as alpha/#bar, that value is not considered in the uniqueness of IDs in the XML document because it is is not of attribute type ID.
<test2>
<alpha bar="xyz"/>
<beta bar="abc"/>
<gamma bar="xyz"/>
</test2>
For the getElementById() call to work, the Document has to know the types of its nodes, and the target node must be of the XML ID type for the method to find it. It knows about the types of its elements via an associated schema. If the schema is not set, or does not declare the id attribute to be of the XML ID type, getElementById() will never find it.
My guess is that your document doesn't know the p element's id attribute is of the XML ID type (is it?). You can navigate to the node in the DOM using getChildNodes() and other DOM-traversal functions, and try calling Attr.isId() on the id attribute to tell for sure.
From the getElementById javadoc:
The DOM implementation is expected to
use the attribute Attr.isId to
determine if an attribute is of type
ID.
Note: Attributes with the name "ID" or
"id" are not of type ID unless so
defined.
If you are using a DocumentBuilder to parse your XML into a DOM, be sure to call setSchema(schema) on the DocumentBuilderFactory before calling newDocumentBuilder(), to ensure that the builder you get from the factory is aware of element types.
ID attribute isn't an attribute whose name is "ID", it's an attribute which is declared to be an ID attribute by a DTD or a schema. For example, the html 4 DTD describes it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
The corresponding xpath expression would actually be id('fribble'), which should return the same result as getElementById. For this to work, the dtd or schema associated with your document has to declare the attribute as being of type ID.
If you are in control of the queried xml you could also try renaming the attribute to xml:id as per http://www.w3.org/TR/xml-id/.
The following will allow you to get an element by id:
public static Element getElementById(Element rootElement, String id)
{
try
{
String path = String.format("//*[#id = '%1$s' or #Id = '%1$s' or #ID = '%1$s' or #iD = '%1$s' ]", id);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xPath.evaluate(path, rootElement, XPathConstants.NODESET);
return (Element) nodes.item(0);
}
catch (Exception e)
{
return null;
}
}

Categories

Resources