Tuesday, September 25, 2007

Process XML in Dot Net -> Parse to Object

Here we consider a small aspect found while parsing XML string.
We are using Dot Net (1.1) but we process xml in general (non-dotnet specific version) using the XPath expressions.

Situation is we have XML string format as:

< ns="http://domain.com/codename/MessagesXMLSchema.xsd">
<>task< /ns:EventType>
<>TASK_COMPLETE< /ns:EventName>
<>02000016000004630144000100000070< /ns:JobId>
<>02000016000004630154000200000070< /ns:TaskId>
<>2007-09-06T15:26:25+04:00< /ns:EventDateTime>
< /ns:XMLMessage>
= strXMLMsg



Scene 1:
Dim xmlDoc As New Xml.XmlDocument
xmlDoc.LoadXml(strXMLMsg)
strXPath = "/XMLMessage /EventName"
xmlNode = xmlDoc.SelectSingleNode(strXPath)
strData = xmlNode.InnerText
In this seen we will not be able to get our parsed data. And the issue is the inclusion of the namespace and its prefix.
So to get the parsed data correctly we have to use the way shown in scene 2.

Scene 2:
Dim xmlDoc As New Xml.XmlDocument
xmlDoc.LoadXml(strXMLMsg)
xsn = New Xml.XmlNamespaceManager(xmlDoc.NameTable)
XMLNamespace = "http://domain.com/codename/MessagesXMLSchema.xsd"
XMLNamespacePrefix = "ns"
xsn.AddNamespace(XMLNamespacePrefix , XMLNamespace)
strXPath = "/ns:XMLMessage /ns:EventName"
xmlNode = xmlDoc.SelectSingleNode(strXPath,xsn)
strData = xmlNode.InnerText
In this way we will get our data parsed correctly!

I hope the situation mentioned above is somewhat helpful.
Any questions/issues/suggestions/imporvements - please mention them in your comments.

Have a nice time.

---
hB

1 comment:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!