How to remove attributes of a node (MSXML)

Go To StackoverFlow.com

1

Let's imagine that I have a result of evaluating XPath expression "//node/@*". MSXML6 returns a set of IXMLDOMNode objects which actually are IXMLDOMAttribute object.

Question: Is there a way to remove that attributes having only an IXMLDOMNode object which represent the attribute?

The problem is that MSXML allows to remove child nodes only through parent node, but an attribute doesn't have it (parentNode returns NULL). Consequently I can't detach an attribute from a node after being extracted using XPath. Is there a way around?

Thanks.

2012-04-04 04:27
by Ivan Kruglov


3

I think the W3C DOM introduced a property ownerElement but MSXML has never made any attempt to catch up with the W3C DOM. So the best I can think of is XPath and selectSingleNode to find the parent element. Here is an example done with JScript and MSXML 6:

var doc = new ActiveXObject("Msxml2.DOMDocument.6.0");
if (doc.loadXML([
    '<root>',
    ' <foo att="1"/>',
    ' <bar att="2"/>',
    '</root>'
].join('\r\n')))
{
  var attributes = doc.selectNodes('//@att');
  for (var i = attributes.length - 1; i >=  0; i--)
  {

    attributes[i].selectSingleNode('..').removeAttributeNode(attributes[i]);
  }
  WScript.Echo(doc.xml);
}
else
{
  WScript.Echo(doc.xml);
}

The output then is

<root>
        <foo/>
        <bar/>
</root>

so the approach works. I realize you don't use JScript but rather probably C++ where you need to add casts to get the right interface exposing a method like removeAttributeNode but the above should suffice to outline the approach.

As a last note, as you haven't mentioned any programming language or environment but only VS 2010, MSXML is meant for native code, if you write managed .NET code with C# or VB.NET then you should use the classes in the namespace System.Xml and below.

2012-04-04 09:03
by Martin Honnen
Ads