属性を持つXMLBeans XmlObject
があるとします。選択した属性を 1 ステップで取得するにはどうすればよいですか?
なんか期待してしまう……。
removeAttributes(XmlObject obj, String[] selectableAttributes){};
上記のメソッドは、XMLObject
これらの属性のみを含む を返すはずです。
前提: から削除する属性XmlObject
は、対応する XML スキーマでオプションである必要があります。この仮定の下で、XMLBeans はいくつかの便利なメソッドを提供します: unsetX
and isSetX
( whereは属性名です。したがって、次の方法でメソッドをX
実装できます。removeAttributes
public void removeAttributes(XmlObject obj,
String[] removeAttributeNames)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException,
NoSuchMethodException {
Class<?> clazz = obj.getClass();
for (int i = 0; i < removeAttributeNames.length; i++) {
String attrName =
removeAttributeNames[i].substring(0, 1).toUpperCase() +
removeAttributeNames[i].substring(1);
String isSetMethodName = "isSet" + attrName;
Boolean isSet = null;
try {
Method isSetMethod = clazz.getMethod(isSetMethodName);
isSet = (Boolean) isSetMethod.invoke(obj, new Object[] {});
} catch (NoSuchMethodException e) {
System.out.println("attribute " + removeAttributeNames[i]
+ " is not optional");
}
if (isSet != null && isSet.booleanValue() == true) {
String unsetMethodName = "unset" + attrName;
Method unsetMethod = clazz.getMethod(unsetMethodName);
unsetMethod.invoke(obj, new Object[] {});
}
}
}
注 1: メソッド シグネチャのセマンティクスを少し変更しました。2 番目の引数 ( String[]
) は、実際には削除する属性のリストです。removeAttributes
これはメソッド名 ( )unsetX
とより一貫していると思いますisSetX
。
isSetX
注 2: 呼び出す前に呼び出す理由はunsetX
、属性が設定されていない場合に if が呼び出されるためunsetX
です。InvocationTargetException
X
注 3: 必要に応じて例外処理を変更することもできます。
カーソルを使用できると思います...扱いが面倒ですが、リフレクションもそうです。
public static XmlObject RemoveAllAttributes(XmlObject xo) {
return RemoveAllofType(xo, TokenType.ATTR);
}
public static XmlObject RemoveAllofTypes(XmlObject xo, final TokenType... tts) {
printTokens(xo);
final XmlCursor xc = xo.newCursor();
while (TokenType.STARTDOC == xc.currentTokenType() || TokenType.START == xc.currentTokenType()) {
xc.toNextToken();
}
while (TokenType.ENDDOC != xc.currentTokenType() && TokenType.STARTDOC != xc.prevTokenType()) {
if (ArrayUtils.contains(tts, xc.currentTokenType())) {
xc.removeXml();
continue;
}
xc.toNextToken();
}
xc.dispose();
return xo;
}
この単純な方法を使用して、要素内のすべてをクリーンアップしています。属性のみを削除するには、 cursor.removeXmlContentsを省略できます。2 番目のカーソルは、最初の位置に戻るために使用されます。
public static void clearElement(final XmlObject object)
{
final XmlCursor cursor = object.newCursor();
cursor.removeXmlContents();
final XmlCursor start = object.newCursor();
while (cursor.toFirstAttribute())
{
cursor.removeXml();
cursor.toCursor(start);
}
start.dispose();
cursor.dispose();
}