XML SAX getValues() 的空控制
Null control with XML SAX getValues()
我正在尝试解析以下 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
<graph mode="static" defaultedgetype="directed">
<nodes>
<node id="0" label="Hello" />
<node id="1" label="Word" />
<node id="2" />
</nodes>
<edges>
<edge id="0" source="0" target="1" />
<edge id="1" source="1" target="2" weight="2.0" />
</edges>
</graph>
</gexf>
可以看出,有些边有权重,有些没有。
我的代码如下:
elif name == "edge":
u = attrs.getValue("source")
v = attrs.getValue("target")
w = attrs.getValue("weight")
if w is not None:
self.edgeweight = w
这里我希望 w 在 XML 文件的第一行是 None,在第二行是 2.0。相反,我得到的只是一个错误。控制它的正确方法是什么?
尝试以下方法。
if attrs.hasKey("weight"):
w = attrs.getValue("weight")
self.edgeweight = w
我参考了this。它没有指定是否可以使用"weight" in attrs
,但您可以尝试看看它是否有效。
get() 方法成功了。
w = attrs.get("weight")
if w is not None:
self.weighted = True
self.edgeweight = float(w)
我正在尝试解析以下 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">
<graph mode="static" defaultedgetype="directed">
<nodes>
<node id="0" label="Hello" />
<node id="1" label="Word" />
<node id="2" />
</nodes>
<edges>
<edge id="0" source="0" target="1" />
<edge id="1" source="1" target="2" weight="2.0" />
</edges>
</graph>
</gexf>
可以看出,有些边有权重,有些没有。
我的代码如下:
elif name == "edge":
u = attrs.getValue("source")
v = attrs.getValue("target")
w = attrs.getValue("weight")
if w is not None:
self.edgeweight = w
这里我希望 w 在 XML 文件的第一行是 None,在第二行是 2.0。相反,我得到的只是一个错误。控制它的正确方法是什么?
尝试以下方法。
if attrs.hasKey("weight"):
w = attrs.getValue("weight")
self.edgeweight = w
我参考了this。它没有指定是否可以使用"weight" in attrs
,但您可以尝试看看它是否有效。
get() 方法成功了。
w = attrs.get("weight")
if w is not None:
self.weighted = True
self.edgeweight = float(w)