Java 从XMLBean中删除属性
假设有一个包含属性的实例,如何在单个步骤中获取选定的属性 我在期待什么Java 从XMLBean中删除属性,java,xml,xmlbeans,Java,Xml,Xmlbeans,假设有一个包含属性的实例,如何在单个步骤中获取选定的属性 我在期待什么 removeAttributes(XmlObject obj, String[] selectableAttributes){}; 现在,上面的方法应该返回只有这些属性的XMLObject。假设:要从XMLObject中删除的属性在相应的XML模式中必须是可选的。在此假设下,XMLBeans为您提供了两种有用的方法:unset和isSetX(其中X是您的属性名。因此,我们可以通过以下方式实现removeAttributes
removeAttributes(XmlObject obj, String[] selectableAttributes){};
现在,上面的方法应该返回只有这些属性的
XMLObject
。假设:要从XMLObject
中删除的属性在相应的XML模式中必须是可选的。在此假设下,XMLBeans为您提供了两种有用的方法:unset
和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[] {});
}
}
}
public void removeAttributes(XmlObject obj,
字符串[]removeAttributeNames)
抛出IllegalArgumentException,IllegalAccessException,
InvocationTargetException、SecurityException、,
NoSuchMethodException{
Class clazz=obj.getClass();
for(int i=0;i
注1:我稍微修改了方法签名的语义:第二个参数(String[]
)实际上是要删除的属性列表。我认为这与方法名称(removeAttributes
)更一致,而且它还简化了事情(使用unset
和isSetX
)
注2:在调用unsetX
之前调用isSetX
的原因是unsetX
如果在未设置属性X
时调用,则会抛出InvocationTargetException
注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;
}
我使用这个简单的方法来清理元素中的所有内容。您可以省略光标。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();
}
我期待的不是反射,因为反射很慢。非常感谢您的时间和回答。如果您想使用XMLBeans,我看不到任何其他方法。或者,您可以在DOM级别工作。