how to check a node whether exist before item("name") under System.Xml.XmlNode?
-
07 Mart 2012 Çarşamba 08:25
node.Item("SendingTime") will get error if not exist in xml file
if not knowing the structure or path in xml file of specific node
how to check whether exist
node = new System.Xml.XmlNode node.Item("SendingTime")
Tüm Yanıtlar
-
07 Mart 2012 Çarşamba 10:29
Can you post a small but complete example allowing us to reproduce the problem and also show us the exact error message?
When I do
XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<root> <foo> <bar>bar 1</bar> </foo> <foo/> </root>"); foreach (XmlNode foo in doc.SelectNodes("root/foo")) { XmlNode bar = foo["bar"]; if (bar != null) { Console.WriteLine("bar InnerText: {0}.", bar.InnerText); } else { Console.WriteLine("No bar element found."); } }then the output is
bar InnerText: bar 1.
No bar element found.so I don't get any error.
The same sample in VB looks like
Dim doc As New XmlDocument() doc.LoadXml("<root><foo><bar>bar 1</bar></foo><foo/></root>") For Each foo As XmlNode In doc.SelectNodes("root/foo") Dim bar As XmlNode = foo.Item("bar") If bar IsNot Nothing Then Console.WriteLine("bar InnerText is {0}.", bar.InnerText) Else Console.WriteLine("No bar element found.") End If Next
Again the attempt to access the bar child element itself does not cause any error, of course you have to check then whether you got an object or null (C#) respectively Nothing (VB).MVP Data Platform Development My blog
-
08 Mart 2012 Perşembe 01:15
as yesterday in debug mode watch list, tried node.item("name") return throw exception in F#
so haven't really use <> null in code
now this works.
人工低的人教人工高的人, 這又是什麼世界