Word XML: Dealing with Optional Attributes

Published 12 December 03 07:56 AM | chris 
I'll get back to my XML Office 2003 issues tomorrow, but for now wanted to share an interesting post from the newsgroups.

Cyril posted the following to me in the newgroups a few weeks ago and I thought I'd publish it here.
----------
I have finally found some time to exercise a workaround for this problem. Note that my original description of the bug was not complete: the problem happens for optional attributes _with a default value_. In this case, the XML node returned by Word is immutable.

For example:

<xs:complexType name="MyStringType">
  <xs:simpleContent>
    <xs:extension base="xs:string">
      <xs:attribute name="myAttribute" type="xs:boolean" use="optional"
default="false"/>
    </xs:extension>
  </xs:simpleContent>
</xs:complexType>

To modify the attribute, you must indeed create a new node and insert it to the attribute list. Here is the new version of SetAttributeValue (note: to simplify the API, I assume that the attributes are unqualified and I omit the namespace).

public static void SetAttributeValue(MSWord.XMLNode node, string attrName,
string attrValue) {
  MSWord.XMLNode attr = GetAttributeByName(node, attrName);
  if (attr == null) { // attribute does not exist, create it.
    object missing = Type.Missing;
    attr = node.Attributes.Add(attrName, null, ref missing);
  }
  attr.NodeValue = attrValue;
  // Workaround problem with optional attribute that have a default value.
  // In that case, the returned XMLNode is immutable.
  // We must check that the new value has been set and create a new node if
necessary
  if (attr.NodeValue != attrValue) {
    object missing = Type.Missing;
    attr = node.Attributes.Add(attrName, null, ref missing);
    attr.NodeValue = attrValue;
  }
}

As you can see, the workaround is a little awkward but I cannot think of anything better.

Comments

No Comments
Anonymous comments are disabled