How to get a XmlFile from a PsiFile

I have a PsiFile which happens to contain Xml, and I'd like to be able to use this as a XmlFile and ultimately a XmlDocument so that I can parse the file. Is there a way to do this? I can't seem to find anything about it.


Comment actions Permalink

If you are doing a lot of DOM work, you may wish to check out the DOM API here
You should also check out the IDEA Architecture here - which contains this information

Give the documentation a read to find your answer, and if you're still having issues just ask! :)

Comment actions Permalink

The first link is what I was using to get as far as I did, but every place they get the XmlFile they just have "...".

But I think the 2nd link is helping me out, but still having some issues. This is what I have:

Project project = e.getData(PlatformDataKeys.PROJECT);
        PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        if(psiFile == null || editor == null) {
             FileViewProvider viewProvider = psiFile.getViewProvider();
             XmlFile xmlFile = (XmlFile) viewProvider.getPsi(StdLanguages.XML);

When I'm debugging, xmlFile is null. One thing I should point out is my file is not actually a .xml file extension. It's a custom extension (example file.test) that really just contains an xml tree. This cannot be changed.

Comment actions Permalink

You should register a file type provider, which can associate your file extension to the XmlFile type --

  • Update your plugin.xml to use the fileTypeFactory extension point

          <fileTypeFactory implementation=""/>

  • Your class should extend fileTypeFactory and provide a method for createFileTypes
  •   def createFileTypes(consumer: FileTypeConsumer) =
        consumer.consume(XmlFileType.INSTANCE, "YourFileExtension")
    Your file extension should now be associated with an Xml file type

  • Update your action - you should be able to treat your file as XML
  •     public void actionPerformed(AnActionEvent e) {
            PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
            if(psiFile != null && psiFile.getFileType() == StdFileTypes.XML) {
                XmlFile xmlFile = (XmlFile) psiFile;
                // ... System.out.println("Opened Xml file " + xmlFile.getText());

Hopefully this helps :)

Please sign in to leave a comment.