You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IntelliJ插件开发:如何正确读写PSI文件的XML节点

IntelliJ插件XML文件处理方案

1. PsiFile转XmlFile并获取XML结构

直接判断PsiFile类型并强转,即可获取XML的核心操作入口:

// 假设已获取到PsiFile实例psiFile
if (psiFile instanceof XmlFile xmlFile) {
    // 获取XML根标签(直接操作Psi元素的起点)
    XmlTag rootTag = xmlFile.getRootTag();
    
    // 若需要关联的文档对象(用于文本层面的操作)
    Project project = psiFile.getProject();
    PsiDocumentManager docManager = PsiDocumentManager.getInstance(project);
    Document document = docManager.getDocument(xmlFile);
}

2. 遍历所有XML节点

使用PsiRecursiveElementWalkingVisitor递归遍历所有XmlTag节点,快速筛选目标节点:

xmlFile.accept(new PsiRecursiveElementWalkingVisitor() {
    @Override
    public void visitXmlTag(XmlTag tag) {
        super.visitXmlTag(tag);
        // 检查当前节点是否包含android:id属性
        XmlAttribute idAttr = tag.getAttribute("android:id");
        if (idAttr != null) {
            // 此处处理符合条件的节点
        }
    }
});

3. 修改属性与保存文件

所有Psi元素的修改必须包裹在写事务中执行,修改后可选择自动保存:

Project project = psiFile.getProject();
WriteCommandAction.runWriteCommandAction(project, () -> {
    // 假设已找到目标XmlTag和对应的XmlAttribute
    XmlAttribute idAttr = targetTag.getAttribute("android:id");
    if (idAttr != null) {
        // 修改属性值
        idAttr.setValue("@+id/your_new_id");
    }

    // 若需要自动保存文件(可选,用户也可手动保存)
    PsiDocumentManager docManager = PsiDocumentManager.getInstance(project);
    Document document = docManager.getDocument(xmlFile);
    if (document != null) {
        docManager.commitDocument(document);
        FileDocumentManager.getInstance().saveDocument(document);
    }
});

内容的提问来源于stack exchange,提问作者Giobar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:01:10