"AJ" <me@who.knows.where.com> wrote in message news:9q********************************@4ax.com...
I am reading from an XML file to populate a combo box with the value
of an "Name" attribute to several elements. When the user selects an item
from the combo and clicks a command button, my application needs to:
3. Write the value of the ID attribute to another XML file.
I can do everything except steps 1 and 2 ;) I've investigated
XMLAttribute.OwnerElement and
ParentElement.Attributes(AttributeName).InnerText, but what I'm
missing
An XmlAttribute is an XmlNode so it has to have a ParentNode property,
but that's always null because an attribute in XML technically doesn't have
a "parent".
1. Find the parent element of the "Name" attribute
What I see this as asking is either to identify the attribute's OwnerElement,
or perhaps the OwnerElement's ParentNode (?).
I'm going to assume OwnerElement for simplicity, that is your XML element
looks something like this,
<owner name="SelectedValue" id="excalibur-101" />
2. Find the value of the "ID" attribute of the same element
The XmlAttribute, 'Name', is going to be in the same AttributesCollection as
the 'ID' one, so if you are after the OwnerElement then you just get this
collection from its Attributes property.
// Assuming user selected "SelectedValue" in the combo box.
// The following XPath expression finds all XmlElements that
// have a Name attribute whose value is 'SelectedValue'.
//
XmlNodeList nodes = xmlDoc.SelectNodes( "//*[@Name='SelectedValue']");
foreach( XmlNode node in nodes )
{
if ( node.NodeType == XmlNodeType.Element )
{
XmlElement ownerElement = node as XmlElement;
XmlAttribute idAttr = ownerElement.Attributes.ItemOf( "ID");
// Do something with idAttr.
}
}
In other words, how do I convert a String to an XmlAttribute?
(Or an XmlElement, for that matter...)
To answer this question, you would call CreateAttribute( ) on the
XmlDocument and then assign the String to this XmlAttribute's
Value property. Finally, append the XmlAttribute to the Attributes
collection of the element you want it associated with.
To convert a String to an XmlElement, call CreateElement( ) on
the XmlDocument and then call CreateText( ) on XmlDocument
passing the String. On the XmlElement, call AppendChild( ) to
attach the XmlTextNode to the element. Finally, append the Xml-
Element into the XmlDocument at the appropriate place.
Derek Harmon