假设有一个带有属性的XMLBeans XmlObject
,我怎样才能一步获得选定的属性?
我期待类似的东西....
removeAttributes(XmlObject obj, String[] selectableAttributes){};
现在上面的方法应该XMLObject
只返回那些属性。
假设:您要从中删除的属性XmlObject
在相应的 XML 模式中必须是可选的。在这种假设下,XMLBeans 为您提供了几个有用的方法:unsetX
和isSetX
(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:我稍微修改了您的方法签名的语义:第二个参数 (the String[]
) 实际上是您要删除的属性列表。我认为这与方法名称(removeAttributes
)更一致,并且它也简化了事情(使用unsetX
and isSetX
)。
注意 2:在调用isSetX
之前调用的原因unsetX
是当属性未设置时unsetX
会抛出一个InvocationTargetException
if called 。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以仅删除属性。第二个光标用于返回初始位置:
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();
}