Minor enhancements to XmlPullWrapper and XmlSerializerWrapper
"Naresh Bhatia" <[email protected]> Thu, 6 Mar 2003 01:01:53 -0500
| Newsgroups | gmane.text.xml.xmlpull.devel |
|---|---|
| Message-ID | <[email protected]> |
Hi Alek,
I have made a minor enhancement to these wrappers to recognize the
xsi:nil attribute. Do you think this should go in to the utility
wrappers you are writing?
Thanks.
Naresh
public class XmlPullWrapper {
static final String
XSI_NS="http://www.w3.org/2001/XMLSchema-instance";
...
/**
* Read the text of a required element and return it or throw
exception if
* required element is not found. Useful for getting the text of
simple
* elements such as <username>johndoe</username>. Assumes that
parser is
* just before the start tag and leaves the parser at the end tag.
If the
* text is nil (e.g. <username xsi:nil="true"/>), then a null will
be returned.
*/
public String getRequiredElementText(String namespace, String name)
throws IOException, XmlPullParserException {
if (name == null) {
throw new XmlPullParserException("name for element can
not be null");
}
String text = null;
nextStartTag(namespace, name);
if (isNil()) {
nextEndTag(namespace, name);
}
else {
text = parser.nextText();
}
parser.require(XmlPullParser.END_TAG, namespace, name);
return text;
}
/**
* Is the current tag nil? Checks for xsi:nil="true".
*/
public boolean isNil()
throws IOException, XmlPullParserException {
boolean result = false;
String value = parser.getAttributeValue(XSI_NS, "nil");
if ("true".equals(value)) {
result = true;
}
return result;
}
}
public class XmlSerializerWrapper {
static final String
XSI_NS="http://www.w3.org/2001/XMLSchema-instance";
/**
* The serializer used to write XML output. It is the responsibility
of the subclass
* to initialize this member.
*/
protected XmlSerializer serializer;
/**
* Writes a simple element such as <username>johndoe</username>. The
namespace
* and elementText are allowed to be null. If elementText is null,
an xsi:nil="true"
* will be added as an attribute.
*/
public void writeSimpleElement(String namespace, String elementName,
String elementText)
throws IOException, XmlPullParserException {
if (elementName == null) {
throw new XmlPullParserException("name for element can not
be null");
}
serializer.startTag(namespace, elementName);
if (elementText == null) {
serializer.attribute(XSI_NS, "nil", "true");
}
else {
serializer.text(elementText);
}
serializer.endTag(namespace, elementName);
}
}