如何识别Eclipse结构化文档中已更改的XML节点?

时间:2011-06-29 12:39:15

标签: xml eclipse events plugins editing

在我自己的Eclipse插件中,我可以使用

IStructuredDocument中捕获编辑事件

IStructuredDocumentListener => void regionChanged(RegionChangedEvent event)

IModelStateListener => void modelChanged(IStructuredModel model)

但我无法看到其中任何一个如何找出DOM中的哪个节点发生了变化。

e.g。以下文件......

<?xml version="1.0" encoding="UTF-8"?>
<doc>
    <element anAttr="fish">blah</element>
</doc>

如果我编辑了 anAttr 的值或元素的文本节点子项

,我想要获得相关DOM节点的事件

1 个答案:

答案 0 :(得分:1)

以下是我为此目的编写的代码片段:

    final ISourceEditingTextTools sourceEditingTextTools = (ISourceEditingTextTools) this.sourceEditor.getAdapter( ISourceEditingTextTools.class );
    final IDOMSourceEditingTextTools domSourceEditingTextTools = (IDOMSourceEditingTextTools) sourceEditingTextTools;
    final Document document = domSourceEditingTextTools.getDOMDocument();

    final INodeAdapter adapter = new INodeAdapter()
    {
        public boolean isAdapterForType( final Object type )
        {
            return false;
        }

        public void notifyChanged( final INodeNotifier notifier,
                                   final int eventType,
                                   final Object changedFeature,
                                   final Object oldValue,
                                   final Object newValue,
                                   final int pos )
        {
            /* System.err.println( "notifyChanged" );
            System.err.println( "  notifier = " + notifier.getClass().getName() );
            System.err.println( "  eventType = " + eventType );
            System.err.println( "  changedFeature = " + ( changedFeature == null ? "null" : changedFeature.getClass().getName() ) );
            System.err.println( "  oldValue = " + ( oldValue == null ? "null" : oldValue.getClass().getName() ) );
            System.err.println( "  newValue = " + ( newValue == null ? "null" : newValue.getClass().getName() ) );
            System.err.println( "  pos = " + pos ); */

            if( eventType == INodeNotifier.ADD && newValue instanceof IDOMNode )
            {
                addAdapter( (IDOMNode) newValue, this );
            }

            handleXmlNodeChange( (Node) notifier );
        }
    };

    addAdapter( (IDOMNode) document, adapter );

    ...

private static void addAdapter( final IDOMNode node,
                                final INodeAdapter adapter )
{
    node.addAdapter( adapter );

    final NodeList children = node.getChildNodes();

    for( int i = 0, n = children.getLength(); i < n; i++ )
    {
        addAdapter( (IDOMNode) children.item( i ), adapter );
    }
}