下面列出了怎么用com.intellij.psi.xml.XmlAttribute的API类实例代码及写法,或者点击链接到github查看源代码。
@Nullable
@Override
public String getRouteName() {
XmlTag defaultTag = PsiTreeUtil.getParentOfType(this.psiElement, XmlTag.class);
if(defaultTag != null) {
XmlTag routeTag = PsiTreeUtil.getParentOfType(defaultTag, XmlTag.class);
if(routeTag != null) {
XmlAttribute id = routeTag.getAttribute("id");
if(id != null) {
return id.getValue();
}
}
}
return null;
}
/**
* Get the "for IN" variable identifier as separated string
* <p>
* {% for car in "cars" %}
* {% for car in "cars"|length %}
* {% for car in "cars.test" %}
*/
@NotNull
public static Collection<String> getForTagIdentifierAsString(XmlTag forTag) {
XmlAttribute each = forTag.getAttribute("each");
if (each == null || each.getValueElement() == null) {
return ContainerUtil.emptyList();
}
PsiElement fluidElement = FluidUtil.retrieveFluidElementAtPosition(each.getValueElement());
if (fluidElement == null) {
return Collections.emptyList();
}
PsiElement deepestFirst = PsiTreeUtil.getDeepestFirst(fluidElement);
return FluidTypeResolver.formatPsiTypeName(deepestFirst);
}
@Override
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
if (context.getLanguage() == XMLLanguage.INSTANCE) return;
final Project project = context.getProject();
if (!FluidIndexUtil.hasFluid(project)) return;
final PsiElement parent = context.getParent();
if (context instanceof XmlAttributeValueImpl && parent instanceof XmlAttribute) {
final int length = context.getTextLength();
final String name = ((XmlAttribute) parent).getName();
if (isInjectableAttribute(project, length, name)) {
registrar
.startInjecting(FluidLanguage.INSTANCE)
.addPlace(null, null, (PsiLanguageInjectionHost) context, ElementManipulators.getValueTextRange(context))
.doneInjecting();
}
}
}
/**
* 判断是否是资源文件
*
* @param bindingElement
* @return
*/
public static boolean isRes(PsiElement bindingElement) {
if (bindingElement instanceof XmlToken) {
XmlToken xmlToken = (XmlToken) bindingElement;
List<String> layouts = BeetlHtmlLineUtil.showBeetlLayout(xmlToken);
List<String> includes = BeetlHtmlLineUtil.showBeetlInclude(xmlToken);
return layouts.size() > 0 || includes.size() > 0;
}
if (!(bindingElement instanceof XmlAttribute)) {
return false;
}
XmlAttribute attribute = (XmlAttribute) bindingElement;
String name = Strings.nullToEmpty(attribute.getName());
String path = Strings.nullToEmpty(attribute.getValue());
int sp = path.indexOf("?");
if (sp > -1) {
path = path.substring(0, sp);
}
return resTag.contains(name) && path.startsWith("${") && endWithRes(path);
}
private PsiClass findJavaPsiClass(PsiElement psiElement) {
XmlTag parentOfType = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class);
if (parentOfType.getName().equals("Sqls")) {
XmlAttribute aClass = parentOfType.getAttribute("class");
if (Objects.nonNull(aClass)) {
String value = aClass.getValue();
String[] split = value.split("\\.");
Collection<PsiClass> roleBizImpl = JavaShortClassNameIndex.getInstance().get(split[split.length - 1], psiElement.getProject(), GlobalSearchScope.projectScope(psiElement.getProject()));
for (PsiClass psiClass : roleBizImpl) {
if (psiClass.getQualifiedName().equals(value)) {
return psiClass;
}
}
}
}
return null;
}
private static Template buildTemplate(@NotNull XmlAttribute attr, List<XmlTag> refs) {
//XmlFile containingFile = (XmlFile)attr.getContainingFile();
PsiElement commonParent = PsiTreeUtil.findCommonParent(refs);
TemplateBuilderImpl builder = new TemplateBuilderImpl(attr);
XmlAttributeValue attrValue = attr.getValueElement();
PsiElement valuePsi = attrValue.getFirstChild().getNextSibling();
String flowNameValue = new String(attrValue.getValue());
builder.replaceElement(valuePsi,"PrimaryVariable", new TextExpression(flowNameValue), true);
/*
for (XmlTag ref : refs) {
if (ref.getContainingFile().equals(attr.getContainingFile())) {
XmlAttribute nextAttr = ref.getAttribute(MuleConfigConstants.NAME_ATTRIBUTE);
XmlAttributeValue nextValue = nextAttr.getValueElement();
PsiElement nextValuePsi = nextValue.getFirstChild().getNextSibling();
builder.replaceElement(nextValuePsi, "OtherVariable", "PrimaryVariable",false);
}
}
*/
return builder.buildInlineTemplate();
}
public static void insertSchemaLocationLookup(XmlFile xmlFile, String namespace, String locationLookup) {
final XmlTag rootTag = xmlFile.getRootTag();
if (rootTag == null)
return;
final XmlAttribute attribute = rootTag.getAttribute("xsi:schemaLocation", HTTP_WWW_W3_ORG_2001_XMLSCHEMA);
if (attribute != null) {
final String value = attribute.getValue();
attribute.setValue(value + "\n\t\t\t" + namespace + " " + locationLookup);
} else {
final XmlElementFactory elementFactory = XmlElementFactory.getInstance(xmlFile.getProject());
final XmlAttribute schemaLocation = elementFactory.createXmlAttribute("xsi:schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
schemaLocation.setValue(namespace + " " + locationLookup);
rootTag.add(schemaLocation);
}
}
@Override
public boolean isPlaceForEndpointUri(PsiElement location) {
XmlFile file = PsiTreeUtil.getParentOfType(location, XmlFile.class);
if (file == null || file.getRootTag() == null || !isAcceptedNamespace(file.getRootTag().getNamespace())) {
return false;
}
XmlAttributeValue value = PsiTreeUtil.getParentOfType(location, XmlAttributeValue.class, false);
if (value == null) {
return false;
}
XmlAttribute attr = PsiTreeUtil.getParentOfType(location, XmlAttribute.class);
if (attr == null) {
return false;
}
return attr.getLocalName().equals("uri") && isInsideCamelRoute(location, false);
}
public static void dumpAttrs(String tag, List<XmlAttribute> attrs) {
if (!Logger.loggable(Logger.DEBUG)) {
return;
}
if (attrs == null) {
return;
}
String ret = "[";
for (XmlAttribute attr : attrs) {
ret += attr.getName() + ":" + attr.getValue() + ",";
}
if (ret.lastIndexOf(",") > 0) {
ret = ret.substring(0, ret.lastIndexOf(","));
}
ret = ret + "]";
Logger.debug(tag + ": " + ret);
}
private String decideFillColor(XmlTag group, XmlTag self) {
String result = Configuration.getDefaultTint();
XmlAttribute groupFill;
if ((groupFill = group.getAttribute("fill")) != null) {
result = StdColorUtil.formatColor(groupFill.getValue());
}
XmlAttribute selfFill;
if ((selfFill = self.getAttribute("fill")) != null) {
result = StdColorUtil.formatColor(selfFill.getValue());
}
XmlAttribute id = self.getAttribute("class");
String colorFromStyle;
if (id != null && id.getValue() != null && (colorFromStyle = styleParser.getFillColor(id.getValue())) != null) {
result = colorFromStyle;
}
return result;
}
public Map<String, String> getChildAttrs(XmlTag tag) {
Map<String, String> styles = new HashMap<String, String>();
XmlAttribute attrs[] = tag.getAttributes();
for (XmlAttribute attr : attrs) {
if (attr.getName().equals("style")) {
String stylesValue = tag.getAttributeValue("style").replaceAll("\\s*", "");
String[] list = stylesValue.split(";");
for (String s : list) {
String[] item = s.split(":");
if (item[0].equals("fill")) {
item[1] = StdColorUtil.formatColor(item[1]);
}
styles.put(item[0], item[1]);
}
} else {
if (attr.getName().equals("fill")) {
styles.put(attr.getName(), StdColorUtil.formatColor(tag.getAttributeValue(attr.getName())));
} else {
styles.put(attr.getName(), tag.getAttributeValue(attr.getName()));
}
}
}
Logger.debug(tag.getName() + styles.toString());
return styles;
}
public XmlTag trim(XmlTag rootTag, List<XmlAttribute> attr) {
Logger.debug("Current tag: " + rootTag.getName());
CommonUtil.dumpAttrs("current attr", Arrays.asList(rootTag.getAttributes()));
CommonUtil.dumpAttrs("parent attr", attr);
if (attr == null) {
attr = new ArrayList<XmlAttribute>();
attr.addAll(Arrays.asList(rootTag.getAttributes()));
}
XmlTag[] subTags = rootTag.getSubTags();
List<XmlAttribute> attrs = new ArrayList<XmlAttribute>();
if (subTags.length == 1 && subTags[0].getName().equals("g")) {
Logger.debug("Tag" + rootTag + " has only a subTag and the tag is 'g'");
Collections.addAll(attrs, subTags[0].getAttributes());
attrs.addAll(attr);
rootTag = trim(subTags[0], attrs);
} else if (subTags.length > 0 && AttrMapper.isShapeName(subTags[0].getName())) {
Logger.debug(rootTag.getSubTags()[0].getName());
Logger.debug("Tag" + rootTag + " is correct tag.");
for (XmlAttribute attribute : attr) {
Logger.debug(attribute.getName() + ":" + attribute.getValue());
}
return AttrMergeUtil.mergeAttrs((XmlTag) rootTag.copy(), reduceAttrs(attr));
}
return rootTag;
}
@Nullable
public static PsiElement getXmlRouteNameTarget(@NotNull XmlFile psiFile,@NotNull String routeName) {
XmlDocumentImpl document = PsiTreeUtil.getChildOfType(psiFile, XmlDocumentImpl.class);
if(document == null) {
return null;
}
for(XmlTag xmlTag: PsiTreeUtil.getChildrenOfTypeAsList(psiFile.getFirstChild(), XmlTag.class)) {
if(xmlTag.getName().equals("routes")) {
for(XmlTag routeTag: xmlTag.getSubTags()) {
if(routeTag.getName().equals("route")) {
XmlAttribute xmlAttribute = routeTag.getAttribute("id");
if(xmlAttribute != null) {
String attrValue = xmlAttribute.getValue();
if(routeName.equals(attrValue)) {
return xmlAttribute;
}
}
}
}
}
}
return null;
}
private static void loadTags(XmlTag customTags, LatteXmlFileData data) {
for (XmlTag tag : customTags.findSubTags("tag")) {
XmlAttribute name = tag.getAttribute("name");
XmlAttribute type = tag.getAttribute("type");
if (name == null || type == null || !LatteTagSettings.isValidType(type.getValue())) {
continue;
}
LatteTagSettings macro = new LatteTagSettings(
name.getValue(),
LatteTagSettings.Type.valueOf(type.getValue()),
isTrue(tag, "allowedFilters"),
getTextValue(tag, "arguments"),
isTrue(tag, "multiLine"),
getTextValue(tag, "deprecatedMessage").trim(),
getArguments(tag)
);
data.addTag(macro);
}
}
private static void loadFilters(XmlTag customFilters, LatteXmlFileData data) {
for (XmlTag filterData : customFilters.findSubTags("filter")) {
XmlAttribute name = filterData.getAttribute("name");
if (name == null) {
continue;
}
LatteFilterSettings filter = new LatteFilterSettings(
name.getValue(),
getTextValue(filterData, "description"),
getTextValue(filterData, "arguments"),
getTextValue(filterData, "insertColons")
);
data.addFilter(filter);
}
}
private static void loadFunctions(XmlTag customFunctions, LatteXmlFileData data) {
for (XmlTag filter : customFunctions.findSubTags("function")) {
XmlAttribute name = filter.getAttribute("name");
if (name == null) {
continue;
}
String returnType = getTextValue(filter, "returnType");
LatteFunctionSettings instance = new LatteFunctionSettings(
name.getValue(),
returnType.length() == 0 ? "mixed" : returnType,
getTextValue(filter, "arguments"),
getTextValue(filter, "description")
);
data.addFunction(instance);
}
}
@NotNull
public static List<AndroidView> getIDsFromXML(@NotNull PsiFile f) {
final ArrayList<AndroidView> ret = new ArrayList<AndroidView>();
f.accept(new XmlRecursiveElementVisitor() {
@Override
public void visitElement(final PsiElement element) {
super.visitElement(element);
if (element instanceof XmlTag) {
XmlTag t = (XmlTag) element;
XmlAttribute id = t.getAttribute("android:id", null);
if (id == null) {
return;
}
final String val = id.getValue();
if (val == null) {
return;
}
ret.add(new AndroidView(val, t.getName(), id));
}
}
});
return ret;
}
@NotNull
@Override
public ResolveResult[] multiResolve(boolean b) {
PsiElement element = getElement();
PsiElement parent = element.getParent();
String text = null;
if(parent instanceof XmlText) {
// <route><default key="_controller">Fo<caret>o\Bar</default></route>
text = parent.getText();
} else if(parent instanceof XmlAttribute) {
// <route controller=""/>
text = ((XmlAttribute) parent).getValue();
}
if(text == null || StringUtils.isBlank(text)) {
return new ResolveResult[0];
}
return PsiElementResolveResult.createResults(
RouteHelper.getMethodsOnControllerShortcut(getElement().getProject(), text)
);
}
public static Set<String> getTags(XmlTag serviceTag) {
Set<String> tags = new HashSet<>();
for(XmlTag serviceSubTag: serviceTag.getSubTags()) {
if("tag".equals(serviceSubTag.getName())) {
XmlAttribute attribute = serviceSubTag.getAttribute("name");
if(attribute != null) {
String tagName = attribute.getValue();
if(tagName != null && StringUtils.isNotBlank(tagName)) {
tags.add(tagName);
}
}
}
}
return tags;
}
@NotNull
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
if (!Symfony2ProjectComponent.isEnabled(holder.getProject())) {
return super.buildVisitor(holder, isOnTheFly);
}
return new PsiElementVisitor() {
@Override
public void visitElement(PsiElement element) {
if(element instanceof XmlAttribute) {
registerXmlAttributeProblem(holder, (XmlAttribute) element);
} else if(element instanceof YAMLKeyValue) {
registerYmlRoutePatternProblem(holder, (YAMLKeyValue) element);
}
super.visitElement(element);
}
};
}
@Nullable
private static SchemaPrefix findAttributeSchema(XmlTag context, String namespacePrefix, int offset) {
for (XmlAttribute attribute: context.getAttributes()) {
if (attribute.getName().startsWith(namespacePrefix)) {
return new SchemaPrefix(attribute, TextRange.create(offset, namespacePrefix.length()), namespacePrefix.substring(offset));
}
}
return null;
}
@Override
public void visitXmlAttribute(XmlAttribute attribute) {
if (attribute.getName().startsWith("xmlns:") && attribute.getValue() != null) {
if (attribute.getValue().startsWith(fluidNamespaceURIPrefix)) {
namespaces.add(new FluidNamespace(attribute.getLocalName(), attribute.getValue().substring(fluidNamespaceURIPrefix.length())));
}
}
super.visitXmlAttribute(attribute);
}
@Override
public void visitXmlTag(XmlTag tag) {
if (tag.getName().equals("f:alias")) {
XmlAttribute map = tag.getAttribute("map");
if (map != null) {
XmlAttributeValue valueElement = map.getValueElement();
if (valueElement != null) {
TextRange valueTextRange = valueElement.getValueTextRange();
PsiElement fluidElement = extractLanguagePsiElementForElementAtPosition(FluidLanguage.INSTANCE, tag, valueTextRange.getStartOffset() + 1);
FluidArrayCreationExpr fluidArray = (FluidArrayCreationExpr) PsiTreeUtil.findFirstParent(fluidElement, x -> x instanceof FluidArrayCreationExpr);
if (fluidArray != null) {
fluidArray.getArrayKeyList().forEach(fluidArrayKey -> {
if (fluidArrayKey.getFirstChild() instanceof FluidStringLiteral) {
String key = ((FluidStringLiteral) fluidArrayKey.getFirstChild()).getContents();
variables.put(key, new FluidVariable(key));
return;
}
variables.put(fluidArrayKey.getText(), new FluidVariable(fluidArrayKey.getText()));
});
}
}
}
}
super.visitXmlTag(tag);
}
/**
* 取得模版文件相对路径
*
* @param bindingElement
* @return
*/
public static String getTemplateFilePathAndName(PsiElement bindingElement) {
if (bindingElement instanceof XmlAttribute) {
return getResPath((XmlAttribute) bindingElement);
} else if (bindingElement instanceof XmlToken) {
return getBeetlResPath((XmlToken) bindingElement);
} else {
throw new RuntimeException("未知类型??请提交issues");
}
}
/**
* 取得静态资源文件${xxx/xx.js}等等类型
*
* @return
*/
private static String getResPath(XmlAttribute attribute) {
String path = Strings.nullToEmpty(attribute.getValue());
int sp = path.indexOf("?");
if (sp > -1) {
path = path.substring(0, sp);
}
int sp2 = path.lastIndexOf("}");
if (sp2 > -1) {
path = path.substring(sp2 + 1);
}
return path;
}
/**
* 判断是sqltoyxml
*
* @param bindingElement
* @return
*/
public static boolean isSqsXmlFile(PsiElement bindingElement) {
if (bindingElement.getContainingFile().getName().endsWith(".xml") && bindingElement instanceof XmlTag) {
XmlTag xmlTag = (XmlTag) bindingElement;
XmlAttribute id = xmlTag.getAttribute("id");
if (xmlTag.getName().equals("sql") && Objects.nonNull(id)) {
return true;
}
}
return false;
}
@Override
public List<PsiElement> findReferences(PsiElement psiElement) {
XmlTag xmlTag = (XmlTag) psiElement;
XmlAttribute xmlAttribute = xmlTag.getAttribute("id");
if (xmlTag.getName().equals("sql") && Objects.nonNull(xmlAttribute)) {
String id = xmlAttribute.getValue();
PsiClass javaPsiClass = findJavaPsiClass(psiElement);
if (Objects.nonNull(javaPsiClass)) {
return SqlsXmlUtil.findJavaPsiElement(javaPsiClass, id);
}
}
return Arrays.asList();
}
@Override
public void getLookupElements(@NotNull GotoCompletionProviderLookupArguments arguments) {
// find class name of service tag
PsiElement xmlToken = this.getElement();
if(xmlToken instanceof XmlToken) {
PsiElement xmlAttrValue = xmlToken.getParent();
if(xmlAttrValue instanceof XmlAttributeValue) {
PsiElement xmlAttribute = xmlAttrValue.getParent();
if(xmlAttribute instanceof XmlAttribute) {
PsiElement xmlTag = xmlAttribute.getParent();
if(xmlTag instanceof XmlTag) {
String aClass = ((XmlTag) xmlTag).getAttributeValue("class");
if(aClass == null) {
// <service id="Foo\Bar"/>
PhpClassCompletionProvider.addClassCompletion(
arguments.getParameters(),
arguments.getResultSet(),
getElement(),
false
);
} else if(StringUtils.isNotBlank(aClass)) {
// <service id="foo.bar" class="Foo\Bar"/>
LookupElementBuilder lookupElement = LookupElementBuilder
.create(ServiceUtil.getServiceNameForClass(getProject(), aClass))
.withIcon(Symfony2Icons.SERVICE);
LookupElementBuilder lookupElementWithClassName = LookupElementBuilder
.create(aClass)
.withIcon(Symfony2Icons.SERVICE);
arguments.getResultSet().addElement(lookupElement);
arguments.getResultSet().addElement(lookupElementWithClassName);
}
}
}
}
}
}
@Nullable
@Override
public PsiElement resolve() {
final String elementName = getElementName();
final XmlTag globalElement = MuleConfigUtils.findGlobalElement(myElement, elementName);
if (globalElement != null) {
final XmlAttribute name = globalElement.getAttribute(MuleConfigConstants.NAME_ATTRIBUTE);
return name != null ? name.getValueElement() : null;
}
return null;
}
public static String getMulePath(XmlTag tag) {
final LinkedList<XmlTag> elements = new LinkedList<>();
while (!isMuleTag(tag)) {
elements.push(tag);
tag = tag.getParentTag();
}
String path = "";
for (int i = 0; i < elements.size(); i++) {
final XmlTag element = elements.get(i);
switch (i) {
case 0: {
final XmlAttribute name = element.getAttribute(MuleConfigConstants.NAME_ATTRIBUTE);
if (name != null) {
path = "/" + MulePathUtils.escape(name.getValue()) + getGlobalElementCategory(element);
}
break;
}
default: {
final XmlTag parentTag = element.getParentTag();
int index = 0;
for (XmlTag xmlTag : parentTag.getSubTags()) {
if (xmlTag == element) {
break;
}
final MuleElementType muleElementType = getMuleElementTypeFromXmlElement(xmlTag);
if (muleElementType == MuleElementType.MESSAGE_PROCESSOR) {
index = index + 1;
}
}
path = path + "/" + index;
}
}
}
System.out.println("path = " + path);
return path;
}