Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XML DOM object model changes under .NET

Status
Not open for further replies.

chiph

Programmer
Jun 9, 1999
9,878
US
For anyone used to the MSXML 4.0 DOM object model, I've just discovered that it's been changed under .NET.

Before, you used to be able to access the Text property of an XML Element directly. Create an Element Node off the DOMDocument40 object, and assign a string to it's Text property. When you wanted to get it later, you did a SelectSingleNode, and grabbed the Text property again. Easy.

But under .NET, to assign a value to an Element, you have to do something like this:
Code:
XmlElement SenderElement = m_DomDoc.CreateElement("Sender");
XmlElement IDElement = m_DomDoc.CreateElement("id");
XmlText IDText = m_DomDoc.CreateTextNode("My ID Value Goes Here");
IDElement.AppendChild(IDText);
SenderElement.AppendChild(IDElement);
You have to go through an intermediate step of creating an XmlText object. A hassle, but not too bad. The real pain comes when you go to read the value later:
Code:
public string SenderId 
{
    get 
    {
        XmlNode SenderIdNode = m_DomDoc.SelectSingleNode("//Envelope//Sender//id");
        foreach (XmlNode ChildNode in SenderIdNode.ChildNodes) 
        {
            if (ChildNode.NodeType == XmlNodeType.Text) 
            {
                return ChildNode.Value;
            }
        }
        return string.Empty;
    }
}
Now you have to iterate through the ChildNodes collection, looking for nodes of type XmlNodeType.Text, and only then you can retrieve the value of the element. Obviously, this really is ugly.

My question is: Anyone know any shortcuts? I've been looking at the docs, and there's no .Text property on XmlElement or XmlNode objects. I also didn't see anything in the XPath language to tell it to go one node further. I'd appreciate another set of eyes looking at this, as I'm just not seeing it.

Thanks.
Chip H.
 
OK, found the answer.

It turns out that XPath has a text() function which returns the text node(s) under your element node. The code to get a value then becomes:
Code:
public string SenderId 
{
    get 
    {
        XmlNode SenderIdNode = m_DomDoc.SelectSingleNode("//Envelope//Sender//id//text()");
        return (SenderIdNode == null) ? string.Empty : SenderIdNode.Value;
    }
}

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top