Search code examples
xmldomattributesappendchildxmlnode

Error when appending a node of XmlNodeType::Attribute to an XmlNode


Could someone please explain what I am doing here wrong that I get this error:

The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type.

on the last line in this code?

XmlDocument^ xmlDoc = gcnew XmlDocument();
XmlNode^ xmlNode = xmlDoc->CreateNode(XmlNodeType::Element, "QualifyingProperties", "http://uri.etsi.org/01903/v1.3.2#");
XmlNode^ nodAttribute = xmlDoc->CreateNode(XmlNodeType::Attribute, "Target", "http://namespace.123");

xmlNode->AppendChild(nodAttribute);

What would be the correct way to add a node of XmlNodeType::Attribute type to an XmlNode? I'm aware I could create an XmlAttribute and add it to attributes, but I want to find out what's wrong with the way I was trying to do it.


Solution

  • This is because, by definition, attributes are not children of other nodes, so you cannot pass them to AppendChild.

    There is a special place for them:

    xmlNode->Attributes->SetNamedItem(nodAttribute);