下面列出了怎么用com.intellij.psi.xml.XmlFile的API类实例代码及写法,或者点击链接到github查看源代码。
@NotNull
@Override
public Collection<? extends String> getVariants(ConvertContext convertContext) {
if (convertContext == null) return Collections.emptyList();
XmlFile file = convertContext.getFile();
final Set<String> drawableIds = new HashSet<>();
file.accept(new PsiRecursiveElementVisitor() {
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
if (element instanceof XmlTag) {
String drawableId = ((XmlTag) element).getAttributeValue("drawableId", SdkConstants.AUTO_URI);
if(drawableId != null && !drawableId.isEmpty()) {
drawableIds.add(drawableId);
}
}
}
});
return new ArrayList<>(drawableIds);
}
public void testGetTargetForXlfAsXmlFileInVersion20Shortcut() {
PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
"<xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\" version=\"2.0\"\n" +
" srcLang=\"en-US\" trgLang=\"ja-JP\">\n" +
" <file id=\"f1\" original=\"Graphic Example.psd\">\n" +
" <skeleton href=\"Graphic Example.psd.skl\"/>\n" +
" <unit id=\"1\">\n" +
" <segment>\n" +
" <source>foo</source>\n" +
" </segment>\n" +
" </unit>\n" +
" </file>\n" +
"</xliff>"
);
Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "foo");
assertNotNull(ContainerUtil.find(files, psiElement ->
psiElement instanceof XmlTag && "foo".equals(((XmlTag) psiElement).getValue().getText()))
);
}
/**
* Looks for the schema file to handle the given namespace (url) within the schemas supported by this provider.
* These schemas are read from spring.schemas file and searched in project files and dependencies. If a schema
* declared in spring.schemas is not present within project files and project dependencies it will not be resolved.
*
* @param url the url of the namespace
* @param module the module where the baseFile is
* @param baseFile the file where the namespace is declared
* @return the schema file for the given url if it is supported by this provider (declared in spring.schemas), otherwise null
*/
@Override
public XmlFile getSchema(@NotNull @NonNls String url, @Nullable final Module module, @NotNull PsiFile baseFile) throws ProcessCanceledException {
if (module == null) {
return null;
}
try {
Map<String, XmlFile> schemas = getSchemas(module);
if (schemas != null) {
XmlFile schemaFile = schemas.get(url);
return schemaFile;
}
} catch (Exception e) {
//e.printStackTrace();
}
return null;
}
@NotNull
public Map<String, XmlFile> getSchemas(@NotNull final Module module) throws ProcessCanceledException {
final Project project = module.getProject();
final CachedValuesManager manager = CachedValuesManager.getManager(project);
final Map<String, XmlFile> bundle = manager.getCachedValue(module, SCHEMAS_BUNDLE_KEY, new CachedValueProvider<Map<String, XmlFile>>() {
public Result<Map<String, XmlFile>> compute() {
try {
return computeSchemas(module);
} catch (ProcessCanceledException pce) {
throw pce;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
}, false);
return bundle == null ? Collections.<String, XmlFile>emptyMap() : bundle;
}
@Nullable
private static String getNamespace(final XmlFile xmlFile, final Project project) {
//Stupid HTTP module XSD weirdo
if (xmlFile.getName().contains("mule-httpn.xsd"))
return "http://www.mulesoft.org/schema/mule/http";
/////
final XmlDocument document = xmlFile.getDocument();
if (document != null) {
final PsiMetaData metaData = document.getMetaData();
if (metaData instanceof XmlNSDescriptorImpl) {
return ((XmlNSDescriptorImpl) metaData).getDefaultNamespace();
}
}
return null;
}
@Nullable
private PsiElement getElement(@Nullable final DataContext context) {
if (context != null) {
final Editor editor = CommonDataKeys.EDITOR.getData(context);
if (editor != null) {
final int offset = editor.getCaretModel().getOffset();
final PsiFile file = CommonDataKeys.PSI_FILE.getData(context);
if (file instanceof XmlFile && MuleConfigUtils.isMuleFile(file)) {
return file.getViewProvider().findElementAt(offset);
}
if (file != null) {
final Language language = PsiUtilCore.getLanguageAtOffset(file, offset);
if (language != file.getLanguage()) {
final PsiFile psiAtOffset = file.getViewProvider().getPsi(language);
if (psiAtOffset instanceof XmlFile && MuleConfigUtils.isMuleFile(psiAtOffset)) {
return psiAtOffset.findElementAt(offset);
}
}
}
}
}
return null;
}
@NotNull
@Override
public DataIndexer<String, Integer, FileContent> getIndexer() {
return inputData -> {
Map<String, Integer> map = new HashMap<>();
PsiFile psiFile = inputData.getPsiFile();
if(!Symfony2ProjectComponent.isEnabledForIndex(psiFile.getProject())) {
return map;
}
if(!ServicesDefinitionStubIndex.isValidForIndex(inputData, psiFile)) {
return map;
}
if(psiFile instanceof YAMLFile) {
map.putAll(getIdUsages((YAMLFile) psiFile));
} else if(psiFile instanceof XmlFile) {
map.putAll(getIdUsages((XmlFile) psiFile));
}
return map;
};
}
@Nullable
private static XmlTag getMatchXmlTag(@NotNull Editor editor, @NotNull PsiFile file) {
if(!(file instanceof XmlFile)) {
return null;
}
int offset = editor.getCaretModel().getOffset();
if(offset <= 0) {
return null;
}
PsiElement psiElement = file.findElementAt(offset);
if(psiElement == null) {
return null;
}
return XmlServiceArgumentIntention.getServiceTagValid(psiElement);
}
@Nullable
private static XmlTag findGlobalElementInFile(Project project, String elementName, VirtualFile file) {
final DomManager manager = DomManager.getDomManager(project);
final PsiFile xmlFile = PsiManager.getInstance(project).findFile(file);
if (isMuleFile(xmlFile)) {
final DomFileElement<Mule> fileElement = manager.getFileElement((XmlFile) xmlFile, Mule.class);
if (fileElement != null) {
final Mule rootElement = fileElement.getRootElement();
final XmlTag[] subTags = rootElement.getXmlTag().getSubTags();
for (XmlTag subTag : subTags) {
if (isGlobalElement(subTag)) {
if (elementName.equals(subTag.getAttributeValue(MuleConfigConstants.NAME_ATTRIBUTE))) {
return subTag;
}
}
}
}
}
return null;
}
@Nullable
private static XmlTag findFlowInFile(Project project, String flowName, VirtualFile file) {
final DomManager manager = DomManager.getDomManager(project);
final PsiFile xmlFile = PsiManager.getInstance(project).findFile(file);
if (isMuleFile(xmlFile)) {
final DomFileElement<Mule> fileElement = manager.getFileElement((XmlFile) xmlFile, Mule.class);
if (fileElement != null) {
final Mule rootElement = fileElement.getRootElement();
final List<Flow> flows = rootElement.getFlows();
for (Flow flow : flows) {
if (flowName.equals(flow.getName().getValue())) {
return flow.getXmlTag();
}
}
final List<SubFlow> subFlows = rootElement.getSubFlows();
for (SubFlow subFlow : subFlows) {
if (flowName.equals(subFlow.getName().getValue())) {
return subFlow.getXmlTag();
}
}
}
}
return null;
}
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);
}
}
private boolean isDevKitConfig(XmlTag tag, XmlFile baseFile) {
Module module = ModuleUtilCore.findModuleForPsiElement(baseFile);
String namespace = tag.getNamespace();
List<XmlSchemaProvider> providers = XmlSchemaProvider.getAvailableProviders(baseFile);
for (XmlSchemaProvider provider : providers) {
Set<String> locations = provider.getLocations(namespace, baseFile);
for (String location : locations) {
XmlFile schema = provider.getSchema(location, module, baseFile);
if (schema != null) {
String schemaFile = schema.getText();
if (schemaFile.contains("http://www.mulesoft.org/schema/mule/devkit")) {
return true;
}
}
}
}
return false;
}
public void testGetTargetForXlfAsXmlFileInVersion12AndResname() {
PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
"<?xml version=\"1.0\"?>\n" +
"<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n" +
" <file source-language=\"en\" datatype=\"plaintext\" original=\"file.ext\">\n" +
" <body>\n" +
" <trans-unit id=\"1\" resname=\"index.hello_world\">\n" +
" <source>foo</source>\n" +
" </trans-unit>\n" +
" </body>\n" +
" </file>\n" +
"</xliff>\n"
);
Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "index.hello_world");
assertNotNull(ContainerUtil.find(files, psiElement ->
psiElement instanceof XmlTag && "index.hello_world".equals(((XmlTag) psiElement).getAttributeValue("resname")))
);
}
@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 void iterateXmlDocumentRoots(Module module, Consumer<XmlTag> rootTag) {
final GlobalSearchScope moduleScope = module.getModuleContentScope();
final GlobalSearchScope xmlFiles = GlobalSearchScope.getScopeRestrictedByFileTypes(moduleScope, XmlFileType.INSTANCE);
ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex();
fileIndex.iterateContent(f -> {
if (xmlFiles.contains(f)) {
PsiFile file = PsiManager.getInstance(module.getProject()).findFile(f);
if (file instanceof XmlFile) {
XmlFile xmlFile = (XmlFile) file;
XmlTag root = xmlFile.getRootTag();
if (root != null) {
rootTag.accept(xmlFile.getRootTag());
}
}
}
return true;
});
}
@NotNull
@Override
public List<TagInfo> getAvailableTagNames(@NotNull XmlFile file, @NotNull XmlTag context) {
List<TagInfo> list = super.getAvailableTagNames(file, context);
list.add(new TagInfo(RTTagDescriptorsProvider.RT_REQUIRE, NS));
list.add(new TagInfo(RTTagDescriptorsProvider.RT_IMPORT, NS));
List<String> importedTags = loadImportedTags(file, context);
for (String importedTag : importedTags) {
list.add(new TagInfo(importedTag, NS) {
@Nullable
@Override
public PsiElement getDeclaration() {
return super.getDeclaration();
}
});
}
return list;
}
@NotNull
@Override
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 visitFile(PsiFile psiFile) {
if(psiFile instanceof XmlFile) {
visitXmlFile(psiFile, holder, new ContainerCollectionResolver.LazyServiceCollector(holder.getProject()));
} else if(psiFile instanceof YAMLFile) {
visitYamlFile(psiFile, holder, new ContainerCollectionResolver.LazyServiceCollector(holder.getProject()));
} else if(psiFile instanceof PhpFile) {
visitPhpFile((PhpFile) psiFile, holder);
}
}
};
}
public void testGetTargetForXlfAsXmlFileInVersion20() {
PsiFile fileFromText = PsiFileFactory.getInstance(getProject()).createFileFromText(XMLLanguage.INSTANCE, "" +
"<?xml version=\"1.0\"?>\n" +
"<xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\"\n" +
" version=\"2.0\" srcLang=\"en-US\" trgLang=\"ja-JP\">\n" +
" <file id=\"f1\" original=\"Graphic Example.psd\">\n" +
" <skeleton href=\"Graphic Example.psd.skl\"/>\n" +
" <group id=\"1\">\n" +
" <unit id=\"1\">\n" +
" <segment>\n" +
" <source>foo</source>\n" +
" </segment>\n" +
" </unit>\n" +
" </group>\n" +
" </file>\n" +
"</xliff>"
);
Collection<PsiElement> files = TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) fileFromText, "foo");
assertNotNull(ContainerUtil.find(files, psiElement ->
psiElement instanceof XmlTag && "foo".equals(((XmlTag) psiElement).getValue().getText()))
);
}
@Nullable
public XmlFile getStringTableXml(@NotNull PsiElement elementFromModule) {
Module module = ModuleUtil.findModuleForPsiElement(elementFromModule);
if (module == null) {
return null;
}
ArmaPluginModuleData data = moduleMap.computeIfAbsent(module, module1 -> {
return new ArmaPluginModuleData(module);
});
XmlFile f = data.getStringTableXmlFile();
if (f == null) {
VirtualFile virtFile = ArmaPluginUtil.getStringTableXmlFile(module);
if (virtFile == null) {
return null;
}
XmlFile file = (XmlFile) PsiManager.getInstance(elementFromModule.getProject()).findFile(virtFile);
data.setStringTableXmlFile(file);
return file;
} else {
if (!f.getVirtualFile().exists()) {
data.setStringTableXmlFile(null);
return null;
}
return f;
}
}
@NotNull
@Override
public DataIndexer<String, String, FileContent> getIndexer() {
return inputData -> {
Map<String, String> map = new HashMap<>();
PsiFile psiFile = inputData.getPsiFile();
if(!Symfony2ProjectComponent.isEnabledForIndex(psiFile.getProject())) {
return map;
}
if(!ServicesDefinitionStubIndex.isValidForIndex(inputData, psiFile)) {
return map;
}
if(psiFile instanceof YAMLFile) {
attachTHashMapNullable(YamlHelper.getLocalParameterMap(psiFile), map);
} else if(psiFile instanceof XmlFile) {
attachTHashMapNullable(XmlHelper.getFileParameterMap((XmlFile) psiFile), map);
}
return map;
};
}
public SVGParser(XmlFile svg, String dpi) {
styles = new HashMap<String, String>();
this.svg = svg;
this.dpi = dpi;
parseDimensions();
XmlDocument document = svg.getDocument();
if (document != null) {
XmlTag rootTag = document.getRootTag();
if (rootTag != null) {
XmlTag[] subTags = rootTag.getSubTags();
for (XmlTag tag : subTags) {
getChildAttrs(tag);
}
}
}
}
@NotNull
@Override
public List<TagInfo> getAvailableTagNames(@NotNull XmlFile file, @NotNull XmlTag context) {
List<TagInfo> list = super.getAvailableTagNames(file, context);
list.add(new TagInfo(RTTagDescriptorsProvider.RT_REQUIRE, NS));
list.add(new TagInfo(RTTagDescriptorsProvider.RT_IMPORT, NS));
List<String> importedTags = loadImportedTags(file, context);
for (String importedTag : importedTags) {
list.add(new TagInfo(importedTag, NS) {
@Nullable
@Override
public PsiElement getDeclaration() {
return super.getDeclaration();
}
});
}
return list;
}
public static List<String> loadImportedTags(@NotNull XmlFile file, @NotNull XmlTag context) {
// PsiElement[] arr = file.getRootTag().getChildren();
// Collection<HtmlTag> tags = PsiTreeUtil.findChildrenOfType(file, HtmlTag.class);
PsiElement[] reqTags = PsiTreeUtil.collectElements(file, new PsiElementFilter() {
@Override
public boolean isAccepted(PsiElement element) {
return element instanceof HtmlTag && (((HtmlTag) element).getName().equals(RTTagDescriptorsProvider.RT_REQUIRE) || ((HtmlTag) element).getName().equals(RTTagDescriptorsProvider.RT_IMPORT));
}
});
List<String> importedTags = new ArrayList<String>();
for (PsiElement elem : reqTags) {
String as = ((HtmlTag) elem).getAttributeValue("as");
if (!Strings.isNullOrEmpty(as)) {
importedTags.add(as);
}
}
return importedTags;
}
/**
* Index metadata file with its class and repository.
* As of often class stay in static only context
*/
@Nullable
public static Collection<Pair<String, String>> getClassRepositoryPair(@NotNull PsiFile psiFile) {
Collection<Pair<String, String>> pairs = null;
if(psiFile instanceof XmlFile) {
pairs = getClassRepositoryPair((XmlFile) psiFile);
} else if(psiFile instanceof YAMLFile) {
pairs = getClassRepositoryPair((YAMLFile) psiFile);
} else if(psiFile instanceof PhpFile) {
pairs = getClassRepositoryPair((PsiElement) psiFile);
}
return pairs;
}
/**
* <routes><import resource="FOO" /></routes>
*/
private static void visitXmlFile(@NotNull XmlFile psiFile, @NotNull Consumer<FileResourceConsumer> consumer) {
XmlTag rootTag = psiFile.getRootTag();
if(rootTag == null || !"routes".equals(rootTag.getName())) {
return;
}
for (XmlTag xmlTag : rootTag.findSubTags("import")) {
String resource = xmlTag.getAttributeValue("resource");
if(StringUtils.isBlank(resource)) {
continue;
}
consumer.consume(new FileResourceConsumer(xmlTag, xmlTag, normalize(resource)));
}
}
public void update(AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
if (project == null || !Symfony2ProjectComponent.isEnabled(project)) {
this.setStatus(event, false);
return;
}
Pair<PsiFile, PhpClass> pair = findPhpClass(event);
if(pair == null) {
return;
}
PsiFile psiFile = pair.getFirst();
if(!(psiFile instanceof YAMLFile) && !(psiFile instanceof XmlFile) && !(psiFile instanceof PhpFile)) {
this.setStatus(event, false);
}
}
@NotNull
@Override
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 visitFile(PsiFile psiFile) {
if(psiFile instanceof YAMLFile) {
psiFile.acceptChildren(new YmlClassElementWalkingVisitor(holder, new ContainerCollectionResolver.LazyServiceCollector(holder.getProject())));
} else if(psiFile instanceof XmlFile) {
psiFile.acceptChildren(new XmlClassElementWalkingVisitor(holder, new ContainerCollectionResolver.LazyServiceCollector(holder.getProject())));
}
}
};
}
@Override
public void visitFile(PsiFile psiFile) {
ProblemRegistrar problemRegistrar = null;
if(psiFile instanceof YAMLFile) {
psiFile.acceptChildren(new YmlClassElementWalkingVisitor(holder, problemRegistrar = new ProblemRegistrar()));
} else if(psiFile instanceof XmlFile) {
psiFile.acceptChildren(new XmlClassElementWalkingVisitor(holder, problemRegistrar = new ProblemRegistrar()));
} else if(psiFile instanceof PhpFile) {
psiFile.acceptChildren(new PhpClassWalkingVisitor(holder, problemRegistrar = new ProblemRegistrar()));
}
if(problemRegistrar != null) {
problemRegistrar.reset();
}
super.visitFile(psiFile);
}
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
if (!(mFile instanceof XmlFile)) {
onGetError(new IllegalArgumentException("File is not a strings.xml file."));
return;
}
ApplicationManager.getApplication().runReadAction(() -> {
mAndroidStrings = ParseStringXml.parse(progressIndicator, mFile);
});
}
@Nullable
@Override
public String[][] getDefaultNamespaces(@NotNull XmlFile file) {
return (file.getFileType() == FluidFileType.INSTANCE || file.getFileType() == HtmlFileType.INSTANCE|| file.getFileType() == XmlFileType.INSTANCE) ? new String[][]{
{"f", "http://typo3.org/ns/TYPO3/Fluid/ViewHelpers"},
{"", "http://www.w3.org/1999/html"}
} : null;
}