XmlTag (@NotNull XmlTag itemTag, @NotNull ExternalAnnotation annotation) { @NonNls String annotationFQName = annotation.getAnnotationFQName(); PsiNameValuePair[] values = annotation.getValues(); XmlElementFactory elementFactory = XmlElementFactory.getInstance(myPsiManager.getProject()); XmlTag anchor = null; for (XmlTag itemAnnotation : itemTag.getSubTags()) { String curAnnotationName = itemAnnotation.getAttributeValue("name"); if (curAnnotationName == null) { itemAnnotation.delete(); continue; } if (annotationFQName.equals(curAnnotationName)) { // found tag for same annotation, replacing itemAnnotation.delete(); break; } anchor = itemAnnotation; } XmlTag newAnnotationTag = elementFactory.createTagFromText(createAnnotationTag(annotationFQName, values)); PsiElement addedElement = itemTag.addAfter(newAnnotationTag, anchor); if (!(addedElement instanceof XmlTag)) { throw new IncorrectOperationException("Failed to add annotation " + annotation + " after " + anchor); } return itemTag; }