Для... еще синтаксиса ("еще" см. http://docs.python.org/ref/for.html )
for i in foo:
if i == 0:
break
else:
print("i was never 0")
блок будет обычно выполняться в конце для цикла, если повреждение не назовут.
вышеупомянутый код мог быть эмулирован следующим образом:
found = False
for i in foo:
if i == 0:
found = True
break
if not found:
print("i was never 0")
Ваш пример кода:
myvalue = elem.SelectSingleNode("Type/text()").Value;
- вот где проблема. Выражение XPath, которое вы использовали там, не означает «дать мне текст элемента Type
». Это означает «отдайте мне все дочерние текстовые узлы элемента Type». А пустой элемент не имеет дочерних текстовых узлов (текстовый узел не может быть пустым в модели документа XPath). Если вы хотите получить текстовое значение узла, вы должны использовать:
myvalue = elem.SelectSingleNode("Type").InnerText;
The recommended approach would be to use .NET's new XML API (namely LINQ to XML).
Here is an example:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
String xml = @"<Root><Value></Value></Root>";
var elements = XDocument.Parse(xml)
.Descendants("Value")
.Select(e => e.Value);
}
}
When I'm actually bothering with XML DOM, you could write a helper method along the lines of:
static string NodeValue(XmlNode node, string defaultValue)
{
if (node != null)
return node.Value ?? defaultValue;
return defaultValue;
}
Then you can do the following if you're not sure your node will exist:
string s = NodeValue(elem.SelectSingleNode("Type"), String.Empty);
If keeps your code readable, especially if you're doing this for multiple elements.
All that being said, SelectSingleNode(..) does not return a null value if the tag is empty. The Value attribute will be null however. If you're just trying to work around that, this should do:
string s = elem.SelectSingleNode("Type").Value ?? String.Empty;
Edit: ah, you're using /text() to select the actual text node. You could just get rid of that part of the XPath, but the NodeValue method I supplied should still work (the "?? defaultValue" part is not needed in that case though).
Maybe this will work for you:
string s = elem.SelectSingleNode("somepath") != null ? elem.SelectSingleNode("somepath").value : ""
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.value(VS.71).aspx
Because the "value" returned depends on the NodeType, there is a chance that the node will be interpreted as a type that can return NULL.
You might be better off using:
XmlElement elem = ....
string s = elem.SelectSingleNode("somepath").InnerText;
as XMLNode.InnerText (or XmlNode.InnerXML) will return a string, including an empty string.